Last active
October 12, 2024 20:42
-
-
Save kizzx2/9282ea8b0e016960135d3c9ab88419e1 to your computer and use it in GitHub Desktop.
Run command with environment variables in PowerShell
This file contains 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
$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 | |
} | |
$i++ | |
} | |
while(1) { | |
if($i -ge $args.length) { | |
exit | |
} | |
if(!($args[$i] -Match '^[^ ]+=[^ ]+$')) { | |
break | |
} | |
$key, $val = $args[$i].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 | |
$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
Thanks for sharing!
I make small change at line 29,
$key, $val = $args[$i] -split "=", 2
, to handle=
in env var value.