powershellvariablesget-wmiobject

Powershell: Saving output to variable


I want to save an output to a variable, but it saves more characters than I want to save.

I use: $InstallLocation1 = Get-WmiObject -Class Win32_Product -Filter 'Name like "%FAS%"' | Select InstallLocation

But then my variable contains: @{InstallLocation=C:\Program Files\inray\FAS\}

But the content I need is: C:\Program Files\inray\FAS\


Solution

  • ... |Select-Object <propertyName>,... will create a new object and copy the properties from the input object to the new object - so you end up with a new object that has exactly 1 property named InstallLocation.

    To grab only the value of a single property, use ForEach-Object -MemberName instead:

    $InstallLocation1 = Get-WmiObject -Class Win32_Product -Filter 'Name like "%FAS%"' |ForEach-Object -MemberName InstallLocation
    

    Alternatively you can (ab)use Select-Object's -ExpandProperty parameter to achieve the same outcome:

    $InstallLocation1 = Get-WmiObject -Class Win32_Product -Filter 'Name like "%FAS%"' |Select-Object -ExpandProperty InstallLocation