Skip to content

Instantly share code, notes, and snippets.

@7sDream
Created October 12, 2024 20:50
Show Gist options
  • Save 7sDream/1a8d8f00c45a255686d5d760eade3027 to your computer and use it in GitHub Desktop.
Save 7sDream/1a8d8f00c45a255686d5d760eade3027 to your computer and use it in GitHub Desktop.
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