0

Is there a way to get a copy of all of the current environment variables in powershell? What I want to do is get a copy of $env at a particular point in time, run a batch script that does a bunch of set commands, and then look at $env again and check what has changed. I would then determine which environment variables had been newly set, changed or unset, and then run the appropriate setx commands (or [Environment]::SetEnvironmentVariable($NAME, $value, 'User')), to make the things that have changed in-process to persistent user changes.

I've tried calling .clone() on $env, but that didn't work. Any ideas on how to get a copy of $env or general ideas about how to accomplish what I describe above? Suggestions for a powershell newbie would be appreciated.

2
  • Use the items in the env: drive? Commented Sep 4, 2015 at 20:55
  • How do you make a copy of env:? Commented Sep 4, 2015 at 20:56

2 Answers 2

2

Just retrieve the Env: drive into a variable.

$envVars = Get-ChildItem Env:

I wrote some functions that might be of use to you as well, in this article:

Windows IT Pro: Take Charge of Environment Variables in PowerShell

I presented some functions in the article: Get-Environment (same as Get-ChildItem Env:, but included for completeness), Restore-Environment (restores a saved copy of the environment), and Invoke-CmdScript (runs a cmd.exe shell script [batch file] that adds environment variables and makes them available in PowerShell).

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

Comments

1

There may be a more appropriate way to do it but this should work.

$a = @{}
Get-ChildItem env: | % { $a[$_.Name] = $_.Value }

Comments

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.