I am trying to ascertain whether 2 application version strings are equal in PowerShell and am getting a confusing result:
PS C:\> $version = wmic product where "caption like '%Citrix Workspace Inside%'" get Version PS C:\> $versionString = "126.96.36.199" PS C:\> $version 188.8.131.52 PS C:\> $versionString 184.108.40.206 PS C:\> $version.GetType() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True String System.Object PS C:\> $versionString.GetType() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True String System.Object PS C:\> $version -eq $versionString False
Is it something to do with what’s returned from the ‘wmic’ command? The return type of
Object, an object array so I’ve just indexed it to grab the string I need. Both
$versionString have the same value and type but return False when compared for equality. Any light on this would be greatly appreciated.
First, a warning:
Win32_ProductWMI class (which the
productargument in your
wmiccall implicitly refers to) is best avoided, because it returns only Windows Installer-installed applications, is not query-optimized (even when filtering, all products must be enumerated), and – most importantly – invariably performs consistency checks and potentially triggers repair actions. For background information and an alternative, see this excellent blog post.
WIMC.exeCLI is deprecated in favor of PowerShell’s CIM cmdlets (see below).
The only immediate problem with your code is that the version numbers returned have trailing spaces. Therefore:
# .Trim() removes leading and trailing whitespace. $version.Trim() -eq $versionString
However, its better to use
Get-CimInstance to retrieve information from WMI, as it returns objects whose properties you can access:
$version = ( Get-CimInstance Win32_Product -Filter "caption like '%Citrix Workspace Inside%'" ).Version $version -eq $versionString
$version, i.e. the first object returned, contains the version number of interest, with no need to work around formatting artifacts such as trailing spaces, header lines, or empty lines (as you have to with the text-only output from external programs such as
The fact that
.Version returns the version numbers of all objects returned by the
Get-CimInstance call is owed to PowerShell’s convenient member-access enumeration feature.
- As an aside: While you could improve the efficiency of the
Get-CimInstancecall slightly by including
-Property Version, which only fills in the
.Versionproperty on the objects returned, you’ll still need to use
.Versionafterwards to get the version number.
Answered By – mklement0