gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 08:30:03 25 4
gpt4 key购买 nike

为什么 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com