带有 -ArgumentList 类型命令的`Start-Process PowerShell` 不调用命令

yek*_*chi 1 powershell

我在 powershell 中执行以下几行:

$argList = "-NoExit -NoProfile -Command {Write-Host 'hello world'}";
Start-Process PowerShell -ArgumentList $argList;
Run Code Online (Sandbox Code Playgroud)

我想要的输出是创建一个新的 powershell windows 并输出hello world.

但是我得到的是打开一个新的 powershell 窗口并像Write-Host 'hello world'. 所以在新窗口中实际上并没有执行Write-Host。如何解决这个问题?

The*_*heo 5

问题在于您将脚本块作为文本插入的 $argList 字符串的引用。

尝试以下任一方法:

$argList = "-NoExit -NoProfile `"Write-Host 'hello world'`""                # works
$argList = "-NoExit -NoProfile -Command `"Write-Host 'hello world'`""       # works
$arglist = '-NoExit', '-NoProfile', '-Command', 'Write-Host "hello world"'  # works
$arglist = '-NoExit', '-NoProfile', '-Command', {Write-Host "hello world"}  # works
$argList = '-NoExit -NoProfile -Command', {Write-Host "hello world"}        # works
$argList = '-NoExit -NoProfile -Command', 'Write-Host "hello world"'        # works

Start-Process PowerShell -ArgumentList $argList
Run Code Online (Sandbox Code Playgroud)


mkl*_*nt0 5

Theo 的有益回答提供了有效的解决方案;添加一些背景信息

只有在PowerShell 会话内部直接调用powershell.exeWindows PowerShell CLI [1]时,您才可以单独使用脚本块( { ... }) ;例如:

# Works, but only from inside a PowerShell session.
PS> powershell -NoProfile -Command { Write-Host 'hello world' }
hello world
Run Code Online (Sandbox Code Playgroud)

相比之下,通过调用 CLI 的行为总是像从外部Start-Process调用一样,其中后面的所有内容都-Command被解析为字符串,并且在删除外部"引用后,生成的标记将与空格连接,然后解释为 PowerShell 源代码,就好像您有从 PowerShell 内部提交该代码。

从 PowerShell 内部提交脚本块本身只会输出其逐字内容(除了{}),这就是您所看到的:

# Submitting a script block *definition* without *calling it* prints
# its verbatim content as a string, it is the equivalent of calling .ToString() on it.
PS> {Write-Host 'hello world'}
Write-Host 'hello world'
Run Code Online (Sandbox Code Playgroud)

因此,您可以简单地通过将调用运算符添加&到嵌入脚本块的前面来使您的解决方案正常工作,以确保其执行

# Note the `&` before the script block to ensure that it is *called*.
$argList = "-NoExit -NoProfile -Command & {Write-Host 'hello world'}"
Start-Process pwsh -ArgumentList $argList
Run Code Online (Sandbox Code Playgroud)

pwsh[1] 这与PowerShell (Core) 7+ CLI类似。