如何解决为什么 pwsh.exe 与 Start-Process 结合不直接接受脚本块?
为什么 start-process powershell.exe { Read-Host }
有效,而 start-process pwsh.exe { Read-Host }
无效?
我知道 -ArgumentList
的 start-process
开关,但是在转义引号时它使事情变得更加复杂:
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 会话时(没有 start-process
),仍然可以使用脚本块:
pwsh.exe {
'Hello World.'
Read-Host
}
我在这里遗漏了什么还是有更好/不同的方法允许脚本块与脚本的其余部分并行执行?
解决方法
您没有显示错误消息。 Pwsh 默认为 -file,而 powershell 默认为 -command。从 cmd 运行:
pwsh { 'hi there' }
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.
pwsh -command { 'hi there' }
hi there
使用 start-process -nonewwindow 可以看到错误:
Start-Process -NoNewWindow pwsh.exe { Read-Host }
The argument 'Read-Host' is not recognized as the name of a script file. Check the
spelling of the name,verify that the path is correct and try
again.
Usage: pwsh[.exe] [-Login] [[-File] <filePath> [args]]
[-Command { - | <script-block> [-args <arg-array>]
| <string> [<CommandParameters>] } ]
[-ConfigurationName <string>] [-CustomPipeName <string>]
[-EncodedCommand <Base64EncodedCommand>]
[-ExecutionPolicy <ExecutionPolicy>] [-InputFormat {Text | XML}]
[-Interactive] [-MTA] [-NoExit] [-NoLogo] [-NonInteractive] [-NoProfile]
[-OutputFormat {Text | XML}] [-SettingsFile <filePath>] [-SSHServerMode]
[-STA]
[-Version] [-WindowStyle <style>] [-WorkingDirectory <directoryPath>]
pwsh[.exe] -h | -Help | -? | /?
PowerShell Online Help https://aka.ms/powershell-docs
All parameters are case-insensitive.
"pwsh { 'hi there' } 在 powershell 中有效。我不知道为什么。
.\echoargs { 'hi there' }
Arg 0 is <-encodedCommand>
Arg 1 is <IAAnAGgAaQAgAHQAaABlAHIAZQAnACAA>
Arg 2 is <-inputFormat>
Arg 3 is <xml>
Arg 4 is <-outputFormat>
Arg 5 is <text>
好像会自动运行这个?
pwsh -encodedCommand IAAnAGgAaQAgAHQAaABlAHIAZQAnACAA -inputFormat xml -outputFormat text
,
pwsh 在参数中默认获取文件名。
如果您尝试在 CMD 中运行它,您将看到:
CMD> pwsh { 'Hello!' }
The argument '{' is not recognized as the name of a script file. Check the spelling of the name,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 { ... }
。
但是你可以像这样为 run pwsh 编写更短的命令:
Start-Process pwsh.exe '-c',{
'Hello World.'
Read-Host
}
-
-c
相当于-Command
- 脚本块将转换为参数中的有效字符串
这是一个使用 start-process (powershell 7) 将脚本块发送到新 pwsh 窗口的工作示例
while(1)
{
$script ={ write-host 'Hello World.'
pause
}
start-process -Filepath pwsh.exe -ArgumentList "-Command $script"
pause
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。