powershell - 为什么 pwsh.exe 结合 Start-Process 不直接接受脚本 block ?

标签 powershell powershell-core start-process scriptblock powershell-7.0

为什么 Start-Process powershell.exe { Read-Host } 有效,但 Start-Process pwsh.exe { Read-Host } 无效?

我知道 Start-Process-ArgumentList 开关,但在转义引号时它使事情变得更加复杂:

PowerShell 7.0.3 和 7.2.0-preview.3:

Start-Process pwsh.exe -ArgumentList '-Command "& {
    ''Hello World.''
    Read-Host
}"' -Verb RunAs

PowerShell 5.1:

Start-Process powershell.exe { 
    'Hello World.'
    Read-Host
} -Verb RunAs

另一方面,当创建一个新的 PowerShell session 时(没有 Start-Process),仍然可以使用脚本 block :

pwsh.exe {
    'Hello World.'
    Read-Host
}

我是不是遗漏了什么,或者是否有更好/不同的方法允许脚本 block 与脚本的其余部分并行执行?

最佳答案

pwsh 在参数中默认获取一个文件名。
如果您尝试在 CMD 中运行它,您将看到:

CMD> pwsh { 'Hello!' }
The argument '{' is not recognized as the name of a script file. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Usage: pwsh[.exe] [-Login] [[-File] <filePath> [args]]
                  [-Command { - | <script-block> [-args <arg-array>]
                                | <string> [<CommandParameters>] } ]
(.. other help from pwsh ..)

这意味着如果你想运行一些命令,你必须在参数中写入 -Command { ... }

但是您可以编写更短的命令来运行 pwsh,如下所示:

Start-Process pwsh.exe '-c', {
    'Hello World.'
    Read-Host
}
  1. -c-Command
  2. 的较短等效项
  3. 脚本 block 将转换为参数中的有效字符串

关于powershell - 为什么 pwsh.exe 结合 Start-Process 不直接接受脚本 block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66831986/

相关文章:

powershell - 使用 Azure Powershell 或 Azure CLI 创建 Log Analytics 警报

Azure SQL 使用 PowerShell 和 ServicePrincipal 为 AD 用户授予访问权限

powershell - 在按下 ENTER 之前获取 powershell 当前行

powershell - 使用 PowerShell start-process 和 invoke-command 远程压缩文件

c# - 自定义 PSHostUserInterface 被 Runspace 忽略

powershell - 如何将参数移交给Powershell脚本?

linux - 如何从 powershell 获取主机名?

powershell - Start-Process powershell 找不到指定的

c# - 从提升进程开始非提升进程

powershell - Powershell 中带有元组键的字典