为什么 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
}
-c
是-Command
的较短等效项
- 脚本 block 将转换为参数中的有效字符串
关于powershell - 为什么 pwsh.exe 结合 Start-Process 不直接接受脚本 block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66831986/