Skip to content

Instantly share code, notes, and snippets.

@7sDream
Forked from kizzx2/with-env.ps1
Last active January 9, 2023 23:44
Show Gist options
  • Save 7sDream/c1619bcce15687dbec878df0ae463a04 to your computer and use it in GitHub Desktop.
Save 7sDream/c1619bcce15687dbec878df0ae463a04 to your computer and use it in GitHub Desktop.
Run command with environment variables in PowerShell
function With-Env {
$ori = @{}
Try {
$i = 0
# Loading .env files
# if (Test-Path $args[0]) {
# foreach ($line in (Get-Content $args[0])) {
# if ($line -Match '^\s*$' -Or $line -Match '^#') {
# continue
# }
# $key, $val = $line.Split("=")
# $ori[$key] = if (Test-Path Env:\$key) { (Get-Item Env:\$key).Value } else { "" }
# New-Item -Name $key -Value $val -ItemType Variable -Path Env: -Force > $null
# Write-Output "$key = $val"
# }
# $i++
# }
while (1) {
if ($i -ge $args.length) {
exit
}
if (!($args[$i] -Match '^[^ ]+=[^ ]+$')) {
break
}
$key, $val = $args[$i] -split "=", 2
$ori[$key] = if (Test-Path Env:\$key) { (Get-Item Env:\$key).Value } else { "" }
New-Item -Name $key -Value $val -ItemType Variable -Path Env: -Force > $null
Write-Output "WithEnv: $key => $val"
$i++
}
Invoke-Expression ($args[$i..$args.length] -Join " ")
}
Finally {
foreach ($key in $ori.Keys) {
New-Item -Name $key -Value $ori.Item($key) -ItemType Variable -Path Env: -Force > $null
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment