将 Select-Object 与第一个参数一起使用时,OutVariable 包含不正确的数据

OutVariable contains incorrect data when using Select-Object with the First parameter

 $somevar = Get-Process -OutVariable var | Select-Object -First 5

为什么在这种情况下 $var = $somevar(两者都只有前 5 个对象)?为什么 -OutVariable 不将正确的输出保存到 $var?我很困惑。

C:\> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.14393.206
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.14393.206
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

C:\>  [System.Environment]::OSVersion.Version

Major  Minor  Build  Revision
-----  -----  -----  --------
10     0      14393  0

In Powershell 3.0 optimization was included with Select-Object。您正在查看一项功能

Beginning in Windows PowerShell 3.0, Select-Object includes an optimization feature that prevents commands from creating and processing objects that are not used. When you include a Select-Object command with the First or Index parameter in a command pipeline, Windows PowerShell stops the command that generates the objects as soon as the selected number of objects is generated, even when the command that generates the objects appears before the Select-Object command in the pipeline. To turn off this optimizing behavior, use the Wait parameter.

使用 -Wait 取消此行为。当您这样做时,该命令需要更长的时间,但它允许您预期的行为发生。

如果对任何人都重要,请在脚注中注意优化功能先决条件:

The optimization feature of Select-Object is available only for commands that write objects to the pipeline as they are processed. It has no effect on commands that buffer processed objects and write them as a collection