在Linux上,我可以做:
$ FOO=BAR ./myscript
在设置环境变量FOO的情况下调用myscript。
在PowerShell中是否可能出现类似的情况,即无需首先设置变量,调用命令,然后再次取消设置变量?
为了更清楚地说明我的用例——我不想把它用作脚本的一部分。相反,我有一个第三方脚本,我可以使用环境变量控制其行为,但在本例中,不能使用命令行参数。所以能够在打字之间交替
$ OPTION=1 ./myscript
and
$ ./myscript
会很方便的。
我对这个问题有足够的动力,因此我继续为它编写了一个脚本:with-env.ps1
用法:
with-env.ps1 FOO=foo BAR=bar your command here
# Supports dot-env files as well
with-env.ps1 .\.env OTHER_ENV=env command here
另一方面,如果你安装了Gow,你可以使用env.exe,它可能比我上面写的快速脚本更健壮一些。
用法:
env.exe FOO=foo BAR=bar your command here
# To use it with dot-env files
env.exe $(cat .env | grep.exe -v '^#') SOME_OTHER_ENV=val your command
你可以通过将脚本作为Job运行来实现:
Start-Job -InitializationScript { $env:FOO = 'BAR' } -FilePath .\myscript.ps1 |
Receive-Job -Wait -AutoRemoveJob
你也可以使用Start-Job的ArgumentList参数向脚本传递参数:
$jobArgs = @{
InitializationScript = { $env:FOO = 'BAR' }
FilePath = '.\myscript.ps1'
ArgumentList = 'arg1', 'arg2'
}
Start-Job @jobArgs | Receive-Job -Wait -AutoRemoveJob
优点和缺点
You don't have to reset the environment variable after the script finishes (which would require try / finally to do it correctly even in the presence of exceptions).
The environment variable will be really local to the launched script. It won't affect other, possibly launched in parallel, jobs.
The script will run in its own, somewhat isolated environment. This means that the launched script can't set variables of the main script, it has to write to the success stream (implicitly or by calling another command that already writes to the success stream) to communicate back to the main script. This could be an advantage or a disadvantage, depending on the use case.
我对这个问题有足够的动力,因此我继续为它编写了一个脚本:with-env.ps1
用法:
with-env.ps1 FOO=foo BAR=bar your command here
# Supports dot-env files as well
with-env.ps1 .\.env OTHER_ENV=env command here
另一方面,如果你安装了Gow,你可以使用env.exe,它可能比我上面写的快速脚本更健壮一些。
用法:
env.exe FOO=foo BAR=bar your command here
# To use it with dot-env files
env.exe $(cat .env | grep.exe -v '^#') SOME_OTHER_ENV=val your command