2

When running a powershell script which changes a directory via cd (or set-location/push-location/etc.), the console that the script was run from also ends up in that directory.

Example: script.ps1

cd c:\tmp
# do stuff

If I run this from c:\users\me, i end up in c:\tmp.

PS C:\users\me> .\script.ps1
PS C:\tmp> |

Now I know that I could use push-location and later do pop-location. However this wouldn't work if the script stopped somewhere in the middle (via Exit).

How can I solve this? Why doesn't the script have it's own location stack?

6
  • 1
    You could always use Try/Catch/Finally. Set the current directory path to a variable and then cd c:\tmp before the Try, and have the directory changed to variable in the Finally? Commented Dec 17, 2014 at 16:03
  • 2
    You could instead call with powershell -File .\script.ps1 Commented Dec 17, 2014 at 16:07
  • thx @JClaspill. Finally even works with exit. Commented Dec 17, 2014 at 16:09
  • thx, @arco444. However this only works if the script location is known, I get a problem if it's somewhere on $env:PATH. Commented Dec 17, 2014 at 16:10
  • @IgorLankin What...? What do you mean if the script location is known? From your example you seem to know where it is... Commented Dec 17, 2014 at 16:11

1 Answer 1

2

You could always use Try/Catch/Finally. Set the current directory path to a variable and then cd c:\tmp before the Try, and have the directory changed to variable in the Finally?

Example 1

$path = (Get-Item -Path ".\" -Verbose).FullName
cd c:\temp
Try
{
    #Do stuff
    #exit is fine to use
    #this will output the directory it is in, just to show you it works
    Write-Host (Get-Item -Path ".\" -Verbose).FullName
}
Catch [system.exception]
{
    #error logging
}
Finally
{
    cd $path
}

Example 2 using popd and pushd

pushd c:\temp
Try
{
    #Do stuff
    #exit is fine to use
    #this will output the directory it is in, just to show you it works
    Write-Host (Get-Item -Path ".\" -Verbose).FullName
}
Catch [system.exception]
{
    #error logging
}
Finally
{
    popd
}

I'd also recommend looking at what arco444 suggested, which is calling the powershell script via the -File parameter. Depending on the scenario that might work as an option.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. This solves the issue. I still think the script should have its own location stack, though.
I'd prefer pushd c:\tempand just popd in the finally block. The commands are available since PS 2.0. See technet.microsoft.com/en-us/library/hh849855.aspx
@IgorLankin Added the pushd example for any future viewers. Good stuff!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.