question

pragunsharma-5239 avatar image
0 Votes"
pragunsharma-5239 asked Evgenij-Smirnov answered

Pipeline in Powershell

Hi guys,, this is bothering me..

I was reading about how pipeline works in powershell at
[1]: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_pipelines?view=powershell-7.1#:~:text=A%20pipeline%20is%20a%20series,sent%20to%20yet%20another%20command.

and got to know that pipeline delivers one object at a time.

So, this

 Get-Service | Format-Table -Property Name, DependentServices


is different from this

 Format-Table -InputObject (Get-Service) -Property Name, DependentServices

So here, going by the explanation, in the first case, the Format-Table works on one object at at time and in the second example, Format-Table works on an array of objects. Please correct me if I am wrong.

If this is the case, then I wonder how does Sort-Object and other cmdlets that need to work on collection of data work with pipe character.
When I do :
Get-Service | Sort-Object

How is Sort-Object able to sort if it just gets to work with one object at a time. So, assume there are 100 service objects that are to be passed to Sort-Object. Will Sort-Object be called 100 times (each for one object) and how will that yield in Sorted results that I see on the screen.


windows-server-powershell
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

Evgenij-Smirnov avatar image
0 Votes"
Evgenij-Smirnov answered

Hi,

it all depends on whether the function has to process the collection as a whole (like Sort-Object or Measure-Object) or every member separately (like Foreach-Object or Where-Object).

In the first scenario, the actual processing happens in the End{} scope, while the Process{} scope simply accumulates data coming in from the pipe into an array which then gets processed in the End{} block.

In the second scenario, the actual processing is done in the Process{} scope, and the parameter accepting pipeline input is treated as an array in that scope. So either the objects come from the pipe, then Proces{} gets executed multiple times but each time the array only has one member, or the objects get passed as an array so Process{} is only executed once but over an array containing multiple members.

Make sense?

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.