WMI Class Win32_OperatingSystem Caption Property May Contain a Trailing Space

The WMI Class Win32_OperatingSystem Caption property returns the particular version of Windows, e.g.:

Microsoft Windows Server 2008 R2 Enterprise  or

Microsoft(R) Windows(R) Server 2003, Enterprise Edition

I had a requirement when querying this via PowerShell to take different actions based on whether the OS was some flavour of 2003 or 2008 and was using the following switch statement :


switch ($OperatingSystem.Caption) { "Microsoft Windows Server 2008 R2 Enterprise" {$OSBuild = "2008"; break} "Microsoft(R) Windows(R) Server 2003, Enterprise Edition" {$OSBuild = "2003";    break} "Microsoft(R) Windows(R) Server 2003, Standard Edition" {$OSBuild = "2003";    break} default {$OSBuild = "Unknown"} }

 

However, when querying a 2008 R2 server $OperatingSystem.Caption was not matching “Microsoft Windows Server 2008 R2 Enterprise”. To the naked eye the results looked the same:

However, if you compared them with the Compare-Object cmdlet PowerShell reported them as different:


Compare-Object -ReferenceObject $OperatingSystem.Caption -DifferenceObject "Microsoft Windows Server 2008 R2 Enterprise"

 

They are definitely both String objects:

So what else could be different? How about the String length:

Aha! Turns out the Caption property has a trailing space and consequently there is no match between the two objects. (A comment on the MSDN page also confirms this for Win 7).  We can get round this by removing any trailing spaces with the String Trim method:

Compare-Object -ReferenceObject $OperatingSystem.Caption.Trim() -DifferenceObject "Microsoft Windows Server 2008 R2 Enterprise"

So the switch statement becomes:


switch ($OperatingSystem.Caption.Trim()) { "Microsoft Windows Server 2008 R2 Enterprise" {$OSBuild = "2008"; break} "Microsoft(R) Windows(R) Server 2003, Enterprise Edition" {$OSBuild = "2003";    break} "Microsoft(R) Windows(R) Server 2003, Standard Edition" {$OSBuild = "2003";    break} default {$OSBuild = "Unknown"} }

If you have found this page for this issue then I hope I have saved you some head scratching. :-)