[英]launch powershell and commands at once
if I do this in a powershell:如果我在 powershell 中执行此操作:
echo beep ; echo beep
it prints:它打印:
beep
beep
but if I do this in a regular console:但如果我在常规控制台中执行此操作:
powershell -command { echo beep ; echo beep }
it prints:它打印:
echo beep ; echo beep
what is the correct syntax to obtain the same result ?获得相同结果的正确语法是什么?
Passing a list of commands inside a script block ( { ... }
) to powershell -Command
for execution as-is is only supported from within PowerShell itself , as running powershell -h
will tell you.将脚本块( { ... }
) 内的命令列表传递给powershell -Command
以按powershell -Command
执行仅在 PowerShell 内部支持,因为运行powershell -h
会告诉您。
From outside of PowerShell, simply pass the commands as-is, but preferably inside double quotes, so as to prevent unintended up-front interpretation of the arguments by cmd.exe
:从 PowerShell外部,只需按原样传递命令,但最好在双引号内,以防止cmd.exe
对参数进行意外的预先解释:
powershell -command "echo beep ; echo beep"
Note, however, that cmd.exe
-style environment-variable references (eg, %USER%
) are still expanded up front.但是请注意, cmd.exe
风格的环境变量引用(例如, %USER%
)仍然是预先扩展的。
Alternatively, you could pass a script block (string) [1] preceded by &
, the call operator to ensure the script block's execution , but that is only necessary if you want to pass arguments to the script block:或者,您可以传递一个以&
开头的脚本块(字符串) [1] ,调用运算符以确保脚本块的执行,但仅当您想将参数传递给脚本块时才需要这样做:
powershell -command "& { echo $Args[0]; echo $Args[0] } beep"
beep
is passed as the 1st argument, which the script block references as $Args[0]
. beep
作为第一个参数传递,脚本块将其引用为$Args[0]
。
As an aside: In PowerShell echo
is an alias of Write-Output
, which writes to the success output stream;顺便说一句:在 PowerShell 中echo
是Write-Output
的别名,它写入成功输出流; the output from any command or expression that isn't captured or redirected implicitly goes to the output stream, so that use of echo
/ Write-Output
is generally unnecessary:来自未捕获或重定向隐含任何命令或表达式的输出变为输出流,以便使用echo
/ Write-Output
通常是不必要的:
powershell -command "& { $Args[0]; $Args[0] } beep"
[1] From inside PowerShell, passing a script block to powershell -command
causes the calling PowerShell session to recognize it and to treat the enclosed commands as the ones to pass to the new session to execute. [1] 从 PowerShell内部,将脚本块传递给powershell -command
会导致调用PowerShell 会话识别它并将包含的命令视为要传递给新会话执行的命令。
From outside of PowerShell, {...}
is a string passed to the new session, and it is the new session that then parses that string as PowerShell code.在 PowerShell外部, {...}
是传递给新会话的字符串,然后新会话将该字符串解析为 PowerShell 代码。 Evaluating a script block by itself, without explicit invocation via &
(or .
), simply outputs the literal contents of the script block, which explains your output;单独评估脚本块,无需通过&
(或.
)显式调用,只需输出脚本块的文字内容,这解释了您的输出; you can verify this behavior by submitting您可以通过提交来验证此行为{ echo beep; echo beep }
{ echo beep; echo beep }
at the PowerShell prompt. { echo beep; echo beep }
在 PowerShell 提示符下。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.