在Linux上,我可以做:

$ FOO=BAR ./myscript

在设置环境变量FOO的情况下调用myscript。

在PowerShell中是否可能出现类似的情况,即无需首先设置变量,调用命令,然后再次取消设置变量?

为了更清楚地说明我的用例——我不想把它用作脚本的一部分。相反,我有一个第三方脚本,我可以使用环境变量控制其行为,但在本例中,不能使用命令行参数。所以能够在打字之间交替

$ OPTION=1 ./myscript

and

$ ./myscript

会很方便的。


当前回答

可以将变量作用于函数和脚本。

$script:foo = "foo"
$foo
$function:functionVariable = "v"
$functionVariable

New-Variable也有一个-scope参数,如果你想要正式并使用New-Variable声明你的变量。

其他回答

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

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

可以将变量作用于函数和脚本。

$script:foo = "foo"
$foo
$function:functionVariable = "v"
$functionVariable

New-Variable也有一个-scope参数,如果你想要正式并使用New-Variable声明你的变量。

两种简单的方法:

$env:FOO='BAR'; .\myscript; $env:FOO=''
$env:FOO='BAR'; .\myscript; Remove-Item Env:\FOO

只是从其他答案(谢谢大家)中总结了一些信息,出于某种原因,这些答案不包含纯一行程序。

一般来说,通过参数传递信息给脚本比通过参数传递信息更好 全局(环境)变量。但如果这是你需要做的,你可以这样做:

$env:FOO = 'BAR'; ./myscript

环境变量$env:FOO可以稍后删除,如下所示:

Remove-Item Env:\FOO

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