Use Sort-Object With Better DataTypes

by Mar 24, 2011

This line of code will sort system DLLs based on file version. However, it turns out that it sorts incorrectly:

dir $env:windir\system32 -filter *.dll |`
Select-Object -ExpandProperty VersionInfo |`
Select-Object FileName, ProductVersion | Sort-Object ProductVersion

Sort-Object will sort alphabetically because the property ProductVersion uses a string type. Did you know that Sort-Object will accept script blocks so you can dynamically correct this? Here is the correct version, which will cast the property to the correct data type before sorting it:

dir $env:windir\system32 -filter *.dll |`
Select-Object -ExpandProperty VersionInfo |`
Select-Object FileName, ProductVersion |`
Sort-Object { try {[System.Version]$_.ProductVersion } catch { 0 }}

However, you should note how the script block uses try/catch so if a DLL file uses an invalid version format, these will appear at the beginning of that list so the catch block declares invalid version information to be lower than 0.

 

Twitter This Tip!
ReTweet this Tip!