Search code examples
powershellsortingvariablespipeline

Powershell pipelinevariable lost/overwritten when using Sort-Object. alternative?


I'm running a series of cmdlets in a pipeline, setting a -PipeLineVariable for each, but I'm getting unexpected results due to the use of a Sort-Object cmdlet higher in the pipeline.

For example take the sample code, which is just a portion of my full code. Get-VMhost is pulling random hosts, but my OCD is wanting an alphabetical list and only wanting to select the first 2. As such I am adding a Sort-Object after the Get-VMhost, but that breaks the pipeline variable at the end.

get-vmhost -PipelineVariable VMHost | sort Name | select -first 2 | % {write-host $vmhost} 

VMHost3
VMHost3

Instead, I expected to see

VMHost1
VMHost2

I understand this to be a result of some cmdlets such as Sort-Object as having to aggregate all input to process and then breaking the stream. I sort of understand this.

Without the use of ...

Select -First 2

... I will get the whole dataset and I can simply sort as my final step to sort it all. I could just also add the select -first 2 at the end. I'm just trying to understand the issue and why it happens and if there's an inline workaround up front.

***Edit... I have my answer, which is simply to set the pipelinevariable AT the sort statement. Thanks @mklement0


Solution

  • You simply need to use the common -PipelineVariable parameter with the Sort-Object cmdlet instead of Get-VMHost in order to have the pipeline variable reflect the sorted object sequence.

    A simplified example:

    3, 6, 2, 1 | Sort-Object -PipelineVariable value | Select-Object -First 2 |
      ForEach-Object { $value }
    

    Output:

    1
    2