在新 window 中打开 powershell core 的正确方法是什么?

What's the correct way to open powershell core in a new window?

此命令打开一个新的 powershell window,运行命令,然后退出:

Start-Process powershell { echo "hello"; sleep 1; echo "two"; sleep 1; echo "goodbye" }

如果我改为启动 Powershell Core,它会打开一个新的 window,但新的 window 会立即退出:

Start-Process pwsh { echo "hello"; sleep 1; echo "two"; sleep 1; echo "goodbye" }

使用 pwsh 执行此类调用的正确方法是什么?

不要将脚本块 ({ ... }) 与 Start-Process 一起使用 - 它会将 作为字符串 绑定到 -ArgumentList 参数,这意味着它的 文字内容 - 除了封闭的 {} - 已通过。

  • WindowsPowerShell (powershell.exe)中,CLI的默认参数是-Command.

  • 在PowerShell Core (v6+, pwsh.exe / pwsh)中是-File[1],这就是您的命令失败的原因。

因此,在 PowerShell Core 中,您必须明确使用 -Command (-c):

Start-Process pwsh '-c', 'echo "hello"; sleep 1; echo "two"; sleep 1; echo "goodbye"'

[1] 为了在类 Unix 平台上 中正确支持 PowerShell Core 的使用,此更改是必要的。

此外,如果您 运行 start-process -nonewwindow,您会看到错误消息 "cannot find the file"。 运行 这样的脚本应该可以工作:start-process pwsh .\script.ps1.