Created
July 4, 2019 19:20
-
-
Save mwallner/59bf6ba3b9b52dac3eac3b4e38cc8b97 to your computer and use it in GitHub Desktop.
"mocking" environment variables in a ScriptBlock
This file contains hidden or 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
function Invoke-WithMockedEnv { | |
param( | |
[Parameter(ValueFromPipeline)] | |
[scriptblock]$ScriptBlock, | |
[Hashtable]$mockValues | |
) | |
$originalValues = @{ } | |
foreach ($v in $mockValues.Keys) { | |
$sKey = "env:$v" | |
if (Test-Path $sKey) { | |
Write-Verbose "backing up '$sKey'" | |
$originalValues[$v] = (Get-Item -Path $sKey).Value | |
} | |
else { | |
$originalValues[$v] = $null | |
} | |
Set-Item -Path $sKey -Value $mockValues[$v] | |
} | |
try { | |
& $ScriptBlock | |
} | |
finally { | |
foreach ($v in $originalValues.Keys) { | |
$sKey = "env:$v" | |
Set-Item -Path $sKey -Value $originalValues[$v] | |
} | |
} | |
} | |
function Print-EnvVar($varName) { | |
$envVarName = "env:$varName" | |
if (Test-Path $envVarName) { | |
$v = Get-Item $envVarName | |
Write-Host " (+) $envVarName = $($v.Value)" -ForegroundColor Green | |
} | |
else { | |
Write-Host " (!) $envVarName does not exist" -ForegroundColor Red | |
} | |
} | |
function Print-SomeEnvValues { | |
Print-EnvVar "COMPUTERNAME" | |
Print-EnvVar "weridval" | |
} | |
Write-Host " -- before mock -- " | |
Print-SomeEnvValues | |
Write-Host " -- mocked -- " | |
$mockedVals = @{ | |
COMPUTERNAME = "flynns-box" | |
weridval = "whatever" | |
} | |
Invoke-WithMockedEnv -mockValues $mockedVals { | |
Print-SomeEnvValues | |
} | |
Write-Host " -- after mock -- " | |
Print-SomeEnvValues |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
if you execute this piece of code, it outputs