I am running multiple scripts from the powershell console. These scripts add/modify variables in the env:
drive. Between running each script, I would like to reset the env:
drive to what it was when I opened up the console. Is there a way to save off/copy the env:
drive, and then copy it back at a later point?

- 1,843
- 1
- 19
- 26
2 Answers
The easiest way is to just start another process for each script. Instead of
.\foo.ps1
just use
powershell -file .\foo.ps1
Then each script gets its own process and thus its own environment to mess with. This doesn't work, of course, if those scripts also modify things like global variables you'd rather have retained in between.
On the other hand, saving the state of the environment is fairly simple:
$savedState = Get-ChildItem Env:
And restoring it again:
Remove-Item Env:*
$savedState | ForEach-Object { Set-Content Env:$($_.Name) $_.Value }

- 344,408
- 85
- 689
- 683
You might want to take a look at the PowerShell Community Extensions module. There commands that make managing environment variables easier to do. In particular, Push-EnvironmentBlock
and Pop-EnvironmentBlock
are useful here. "Push" saves the current environment variables and pushes it onto a stack. "Pop" removes the previous state from the stack and restores it. So you would probably do this
Push-EnvironmentBlock -Description "Before running script.ps1"
.\script.ps1
Pop-EnvrionmentBlock

- 39,828
- 3
- 90
- 122