3

I'm new to PowerShell and am just trying to figure out how it works exactly.

So, how can I write this code:

Get-ChildItem C:\ | Sort-Object Length

as multi lined code? I tried this:

$child_items = Get-ChildItem C:\
Sort-Object $child_items Length

but it didn't work. I'm getting:

Sort-Object : A positional parameter cannot be found that accepts argument 'Length'.

3 Answers 3

5

Although the other answers are the right way to pass value using named parameter remember what get-help Sort-Object say:

When you use the InputObject parameter to submit a collection of items, 
Sort-Object receives one object that represents the collection. 
Because one object cannot be sorted, Sort-Object returns the entire collection unchanged.

You'll find that no sort operation will be done passing $child_items to -inputobject.

You always need to pass value with a pipe to -inputobject

Sign up to request clarification or add additional context in comments.

1 Comment

... and if you do not like it, you can vote up this connect item: connect.microsoft.com/PowerShell/feedback/details/568524/…
2

You need to specify the -InputObject parameter. Without it, $child_items will bind to the first positional parameter, which is 'Property'

Sort-Object -InputObject $child_items Length

UPDATE

I'm not removing my answer cause there are comments attached to it. I was wrong, the results from Get-ChildItem are sorted by default and I concluded that passing the array to InputObject does the job. Clearly I was wrong, check @C.B answer.

3 Comments

Although the script runs with this, the objects are no longer sorted. Why's that?
@SebastianKrysmanski What are you doing with the reult of Sort-Object? Remember it does not sort in place.
I just want to write its result to the console (so that it matches the output of the piped alternative).
1

This would work:

Get-ChildItem C:\ | 
Sort-Object Length

Or for you example this would work too;

$child_items = Get-ChildItem C:\
$child_items | Sort-Object Length

You can also use the back tick as a line continuation character .

1 Comment

I would say he should use the backtick ` , because some cmdlets won't run without it, at least not consistently and it makes it more readable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.