Created
October 3, 2019 19:09
-
-
Save lzybkr/fa46d9d50b801ae9cb66ad2bb65f0ef6 to your computer and use it in GitHub Desktop.
Invoke a script block with a temporary environment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
param( | |
[Parameter(Position=0, Mandatory)] | |
[hashtable] | |
$private:Environment, | |
[Parameter(Position=1, Mandatory)] | |
$private:ScriptBlock | |
) | |
end { | |
function ForEachKeyValuePair($hashtable, $scriptblock) { | |
foreach ($entry in $hashtable.GetEnumerator()) { | |
$key = $entry.Key | |
$value = $entry.Value | |
& $scriptblock | |
} | |
} | |
${@@private_backup@@} = @{} | |
ForEachKeyValuePair $Environment { | |
if (Test-Path env:$key) { | |
${@@private_backup@@}[$key] = $value | |
} | |
} | |
ForEachKeyValuePair $Environment { Set-Item env:$key $value } | |
try { | |
& $ScriptBlock | |
} finally { | |
ForEachKeyValuePair $Environment { Remove-Item env:$key } | |
ForEachKeyValuePair ${@@private_backup@@} { Set-Item env:$key $value } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment