Objective
Isolate environmental variable changes to a code block.
Background
If I want to create a batch scrip
I would probably just use a try { } finally { }
:
try {
$OriginalValue = $env:MYLANG
$env:MYLANG= 'GB'
my-cmd dostuff -o out.csv
}
finally {
$env:MYLANG = $OriginalValue
}
That should force the values to be set back to their original values even if an error is encountered in your script. It's not bulletproof, but most things that would break this would also be very obvious that something went wrong.
You could also do this:
try {
$env:MYLANG= 'GB'
my-cmd dostuff -o out.csv
}
finally {
$env:MYLANG = [System.Environment]::GetEnvironmentVariable('MYLANG', 'User')
}
That should retrieve the value from HKEY_CURRENT_USER\Environment
. You may need 'Machine'
instead of 'User'
and that will pull from HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment
. Which you need depends if it's a user environment variable or a computer environment variable. This works because the Env:
provider drive doesn't persist environment variable changes, so changes to those variables won't change the registry.