Use Sort-Object With Better DataTypes

Share |

Join PowerShell.com!
Subscribe to Feed

PowerShell eBook
Sign up for
Your PowerTip of the Day:

Award-winning PowerShellPlus


Admin Guide to PowerShell Remoting


Mastering PowerShell eBook

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!


Posted Mar 24 2011, 08:00 AM by ps1
Copyright 2012 PowerShell.com. All rights reserved.