在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

其他回答

在我的用例中,我需要设置一个环境变量,这样我就可以在Docker撰写脚本中使用它。在我的Powershell脚本中,我使用分号定义变量,然后在同一行上调用docker-compose

$env:PLATFORM="linux/x86_64" ; docker-compose up -d --build

在docker compose中,我现在可以使用我的${PLATFORM}变量。

就像这样

...
services:
  zookeeper:
    image: confluentinc/cp-zookeeper:latest
    platform: ${PLATFORM}
...

你可以通过将脚本作为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.

一个工具使用了一些我无法用pip获取的库。为了将路径保存在一个可记忆的位置,我在全局中设置了$env:PYTHONPATHWAIT。

使用结果是这样的

$env:PYTHONPATH=$env:PYTHONPATHWAIT ; usdcat .\milkyway.usd

通过使用脚本块调用powershell来创建一个“subshell”,允许你对环境进行范围更改:

pwsh -Command { $env:MYVAR="myvalue"; .\path\to.exe }

我对这个问题有足够的动力,因此我继续为它编写了一个脚本: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