Created
February 7, 2023 16:07
-
-
Save MatejKafka/a73178653126f30bf8bc744d5c6bfc29 to your computer and use it in GitHub Desktop.
`fish`-style `env` command, which invokes a command with extra environment variables set
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
# Example: env TEST=1 cmd /c 'echo TEST=%TEST%' | |
function Invoke-WithEnvironment { | |
# parse arguments | |
$NewEnv = @{} | |
$CommandArgs = @() | |
$ParsingEnv = $true | |
foreach ($Arg in $Args) { | |
if ($ParsingEnv) { | |
# FIXME: is this pattern ok? | |
if ($Arg -match '(^[^ ^=]+)=(.*)$') { | |
$NewEnv[$Matches[1]] = $Matches[2] | |
} else { | |
$ParsingEnv = $false | |
$Command = $Arg | |
} | |
} else { | |
$CommandArgs += $Arg | |
} | |
} | |
if ($ParsingEnv) { | |
throw "No command passed." | |
} | |
$OrigEnv = ls Env: | |
try { | |
# set new environment | |
foreach ($e in $NewEnv.GetEnumerator()) { | |
$null = New-Item "Env:$($e.Name)" -Value $e.Value -Force | |
} | |
# for some reason, splatting everything (even the command) doesn't work | |
& $Command @CommandArgs | |
} finally { | |
# revert back to the old environment | |
# remove extra variables | |
ls Env: | ? Name -notin $OrigEnv.Name | % {Remove-Item "Env:$($_.Name)"} | |
# reset values of existing variables | |
foreach ($e in $OrigEnv) { | |
$null = New-Item "Env:$($e.Name)" -Value $e.Value -Force | |
} | |
} | |
} | |
New-Alias env Invoke-WithEnvironment |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment