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.




I want the properties sorted by Name, and then expand the Name.


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!

Sorted properties ðŸŽ‰

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.


That is all for now, hope you learned something ðŸ§  


Comments

Popular posts from this blog

Hidden settings in the Raspberry Pi Imager

Getting the Miyoo Mini Plus battery into Home Assistant

Getting Company Portal apps locally using PowerShell (no auth!)