Search code examples
powershellvirtual-drive

Save off env: drive and later revert


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?


Solution

  • 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 }