Created
October 12, 2024 20:50
-
-
Save 7sDream/1a8d8f00c45a255686d5d760eade3027 to your computer and use it in GitHub Desktop.
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 with-env { | |
$originalEnvValues = @{} | |
$envAssignments = @() | |
$command = @() | |
$isEnvAssignment = $true | |
foreach ($arg in $args) { | |
if ($isEnvAssignment -and $arg -match '=') { | |
$envAssignments += $arg | |
} else { | |
$isEnvAssignment = $false | |
$command += $arg | |
} | |
} | |
foreach ($assignment in $envAssignments) { | |
$envName, $envValue = $assignment -split '=', 2 | |
$originalEnvValues[$envName] = Get-Item "env:$envName" -ErrorAction SilentlyContinue | |
Set-Item "env:$envName" $envValue | |
Write-Output "With-Env: $envName => $envValue" | |
} | |
if ($command.Length -eq 0) { | |
Write-Error "No command" | |
return | |
} | |
try { | |
& $command[0] ($command | select-object -skip 1) | |
} finally { | |
foreach ($envName in $originalEnvValues.Keys) { | |
if ($originalEnvValues[$envName] -eq $null) { | |
Remove-Item "env:$envName" | |
} else { | |
Set-Item "env:$envName" $originalEnvValues[$envName] | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment