Skip to content

Instantly share code, notes, and snippets.

@mwallner
Created July 4, 2019 19:20
Show Gist options
  • Save mwallner/59bf6ba3b9b52dac3eac3b4e38cc8b97 to your computer and use it in GitHub Desktop.
Save mwallner/59bf6ba3b9b52dac3eac3b4e38cc8b97 to your computer and use it in GitHub Desktop.
"mocking" environment variables in a ScriptBlock
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
@mwallner
Copy link
Author

mwallner commented Jul 4, 2019

if you execute this piece of code, it outputs

 -- before mock -- 
 (+) env:COMPUTERNAME = MWINBOX2
 (!) env:weridval does not exist
 -- mocked --
 (+) env:COMPUTERNAME = flynns-box
 (+) env:weridval = whatever
 -- after mock --
 (+) env:COMPUTERNAME = MWINBOX2
 (!) env:weridval does not exist

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment