Skip to content

Instantly share code, notes, and snippets.

@MatejKafka
Created February 7, 2023 16:07
Show Gist options
  • Save MatejKafka/a73178653126f30bf8bc744d5c6bfc29 to your computer and use it in GitHub Desktop.
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
# 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