NEW:
The old approach I originally answered with has a few quirks with environment variables that use a ;
delimiter. I tried compensated by handling PATH seperately, but sometimes there are other such variables.
So this is the new approach; you might want to put it in a script or something. It has to nest a couple of powershell processes real quick, which isn't ideal, but it's the only reliable way I've found to escape the active environment and capture the output.
# Call a powershell process to act as a wrapper to capture the output:
& ([Diagnostics.Process]::GetCurrentProcess().ProcessName) -NoP -c (
# String wrapper to help make the code more readable through comma-separation:
[String]::Join(' ', (
# Start a process that escapes the active environment:
'Start-Process', [Diagnostics.Process]::GetCurrentProcess().ProcessName,
'-UseNewEnvironment -NoNewWindow -Wait -Args ''-c'',',
# List the environment variables, separated by a tab character:
'''Get-ChildItem env: | &{process{ $_.Key + [char]9 + $_.Value }}'''
))) | &{process{
# Set each line of output to a process-scoped environment variable:
[Environment]::SetEnvironmentVariable(
$_.Split("`t")[0], # Key
$_.Split("`t")[1], # Value
'Process' # Scope
)
}}
OLD:
Did my best to try and make it a one-liner, but since the PATH variable needs special handling, I couldn't do it without making a stupidly long line. On the plus side, you don't need to rely on any third-party modules:
foreach ($s in 'Machine','User') {
[Environment]::GetEnvironmentVariables($s).GetEnumerator().
Where({$_.Key -ne 'PATH'}) | ForEach-Object {
[Environment]::SetEnvironmentVariable($_.Key,$_.Value,'Process') }}
$env:PATH = ( ('Machine','User').ForEach({
[Environment]::GetEnvironmentVariable('PATH',$_)}).
Split(';').Where({$_}) | Select-Object -Unique ) -join ';'
The code is scoped to the process, so you don't have to worry about anything getting messed up (not that it would, I tested it).
Note: Neither approach removes uniquely-named environment variables that were created in your active environment, so if you defined $env:FOO = 'bar'
and 'FOO' is not normally one of your environment variables, $env:FOO
will still return bar
even after any of the above code is ran.