首页 > 解决方案 > 在新窗口中打开powershell核心的正确方法是什么?

问题描述

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

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

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

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

用 pwsh 进行这种调用的正确方法是什么?

标签: powershellpowershell-core

解决方案


不要使用{ ... }带有 - 的脚本块 ( ),它作为字符串Start-Process绑定到参数,这意味着它的文字内容- 除了封闭和- 被传递。-ArgumentList{}

  • Windows PowerShell ( 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 平台上的shebang 行中使用 PowerShell Core,此更改是必要的。


推荐阅读