#PSTip Validating version numbers without RegEx

If you have read my earlier post on the Hyper-V Copy-VMFile cmdlet, I was checking for the version of integration components (IC) installed in the virtual machines. I wanted to verify if the IC version is at a minimum supported level or not. If you look at any version number, it usually has four different parts – major, minor, build, and release numbers.

The traditional way of checking for version numbers is to verify if all four version numbers match or not. This can sometimes be complex and error prone. A more easy and efficient way to do that is using System.Version .NET class. This is available as [Version] type accelerator in PowerShell.

PS> [Version]"6.3.9421.0"
Major    Minor    Build    Revision
-----    -----    -----    --------
6        3        9421     0

The [Version] type accelerator automatically converts the string into a System.Version object. It is then easy to perform the required comparisons using the PowerShell comparison operators. This class also has several overloaded methods to check version numbers that do not necessarily have all four components in the a.b.c.d version format.

PS> $PSVersionTable.BuildVersion -eq [Version]"6.3.9423.0"
False

PS> $PSVersionTable.BuildVersion -eq [Version]"6.3.9421.0"
True

PS> $PSVersionTable.BuildVersion -ge [Version]"6.3.9421.0"
True

PS> $PSVersionTable.BuildVersion -le [Version]"6.3.942.0"
False

PS> $PSVersionTable.BuildVersion -le [Version]"6.3.9942.0"
True

PS> $PSVersionTable.BuildVersion -ne [Version]"6.3.9942.0"
True
Share on: