Sorting properties (not objects) in PowerShell
This week I had a need for sorting the properties of an object alphabetically. Funny enough, the aptly named "Sort-Object" does not do this, that cmdlet sorts an array of objects by one or more given property names – useful for listing files in a folder, ordered by the files' size, for example.
But I had to figure out something else. Take this example, just all the properties of a file in default order. Say I want to sort these alphabetically.
First, I need to identify exactly which properties. Get-Member gives you the methods in addition to the properties, I don't want the methods. I just want the different properties, I got those with -MemberType *Property.
Now, store that in a variable, here named $SortedProps. This variable is now a string array.
Now, back to start with the Get-Item of the file. That output gets piped to Select-Object, which has the parameter "Property" that takes a string array. So I feed my $SortedProps into there, and tadaa!
So the idea here is to get a sorted list of all wanted properties of the object, then use Select-Object to get those specific properties in the correct order.
Comments
Post a Comment