首页 > 解决方案 > Powershell变量分配与管道

问题描述

这两个命令之间的根本区别是什么?

$myVar = & "notepad.exe"

& "notepad.exe" | Set-Variable "myVar"

对于第一个,命令立即返回,而无需等待 exe 终止,这不是我所期望的。

对于第二个(或任何其他带有管道的东西,例如| Out-Fileor | Set-Content),该命令会正确等待 exe 将结果写入 stdout 并终止。

标签: powershell

解决方案


Pipeline is nothing but taking the Output from the first set and passing it as an input to the second one. Pipelines act like a series of connected segments of pipe. Items moving along the pipeline must pass through each segment.

In your case, Powershell is actually waiting in both the cases. but if you use Measure-Command, there is a difference in execution time which is better in case of $myVar = & "C:\path to\program.exe" $argument


推荐阅读