Question:
PowerShell 4.0
I read about Sort-Object
cmdlet here (TechNet page). I don’t understand how to use -InputObject
parameter. That page hasn’t examples for it. Also I didn’t find this info in Internet. I would be very grateful for the examples of its using, or for the links to Internet pages with that info.
I have tried to use it how I understand its purpose (according documentation):
1 2 3 |
$items = ('a','b','c','d') $result = sort -InputObject $items -Descending |
But the result
variable has the same value like it has items
instead of its descended version.
Thank you.
Answer:
InputObject
is a generic name used for a parameter that takes pipeline input. It’s part of internal PowerShell naming convention and there is nothing special about it.
Your example doesn’t work as you think it should, because when you pass a collection to the InputObject
parameter it’s treated as a single item and not unwrapped to individial elements, so it doesn’t get sorted. This allows you to sort a collection of collections.
Consider this examples:
This is how Sort-Object
works:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
function Add-Quotes { Param ( [Parameter(ValueFromPipeline = $true)] $InputObject ) Process { "'$InputObject'" } } |
Note that array is automatically unwrapped by the pipeline, then idividial items are assigned the $InputObject
variable in each iteration and then processed in Process
block:
1 2 3 4 5 6 |
PS> $items | Add-Quotes 'a' 'b' 'c' 'd' |
But when you pass a collection to the InputObject
it’s not iterated over, because there is no pipeline to unwrap it:
1 2 3 |
PS> Add-Quotes -InputObject $items 'a b c d' |
Sometimes it’s a desired behavior, sometimes you need to unwrap collections no matter where they came from. In this case you use internal foreach loop to do so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
function Add-Quotes { Param ( [Parameter(ValueFromPipeline = $true)] [string[]]$InputObject ) Process { foreach($item in $InputObject) { "'$item'" } } } PS > $items | Add-Quotes 'a' 'b' 'c' 'd' PS > Add-Quotes -InputObject $items 'a' 'b' 'c' 'd' |
Hope this makes it clear for you.