问题描述
一开始我对 PowerShell ScriptBlock 感到兴奋,但最近我对它在块内的执行顺序感到困惑.例如:
I got excited with PowerShell ScriptBlock at first but I was confused recently with its executing ordering inside blocks. For example:
$test_block = {
write-host "show 1"
ps
write-host "show 2"
Get-Date
}
调用 $test_block.Invoke() 的输出:
The output by calling $test_block.Invoke():
show 1
show 2
<result of command 'ps'>
<result of command 'get-date'>
输出内容的命令会先运行吗?
Do commands who output something run first?
推荐答案
这种行为是因为 write-主机 不会将输出放在管道上.其他命令放置在管道上,因此在函数(调用)返回之前不会输出到屏幕.
This behaviour is because write-host doesn't put the output on the pipeline. The other commands are placed on the pipeline so are not output to the screen until the function (invoke) returns.
要获得我认为您期望的行为,请改用 write-output,所有命令的结果将在管道中返回.
To get the behaviour I believe you were expecting, use write-output instead, the results of all the commands will then be returned in the pipeline.
$test_block = {
write-output "show 1"
ps
write-output "show 2"
Get-Date
}
$test_block.Invoke()
这篇关于PowerShell 脚本块内的命令执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!