Home > Software engineering >  How to prevent Set-Location in powershell script from changing the path of calling shell
How to prevent Set-Location in powershell script from changing the path of calling shell

Time:11-11

Let's say I have a simple powershell script:

# File: myscript.ps1
set-location C:\Windows

Then I invoke this script from the prompt as follows:

PS> Get-Location
C:\User\Dude

PS> .\myscript.ps1

PS> Get-Location
C:\Windows   #!!!!!!!!!

I don't want my script to change the calling shells path... how to prevent this? Can I put something in the code to turn off exporting the PATH to the parent? or is there a way to somehow set it back to the original value before exiting the script, either on error or normal termination?

CodePudding user response:

Rather than

Set-Location C:\Windows

Try using the Push-Location and Pop-Location in your script

 #start of script 
    Push-Location C:\Windows
    ...
    Pop-Location
 #end of script

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/push-location?view=powershell-7.2

When to use Push-Location versus Set-Location?

CodePudding user response:

# Run ScriptBlock from a Temporary Path
function better_with_path {
    param(
        [string]$newpath,
        [ScriptBlock]$action
    )
    
    Push-Location $newpath
    try 
    {
        & $action
    }
    finally
    {
        Pop-Location
    }
}
  • Related