Skip to content

Instantly share code, notes, and snippets.

@lzybkr
Created October 3, 2019 19:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lzybkr/fa46d9d50b801ae9cb66ad2bb65f0ef6 to your computer and use it in GitHub Desktop.
Save lzybkr/fa46d9d50b801ae9cb66ad2bb65f0ef6 to your computer and use it in GitHub Desktop.
Invoke a script block with a temporary environment
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