Categories

Using [wmiclass] accelerator and string substitution

Tripped over an interesting problem

I want to use the [wmiclass] accelerator because I need to find the key of a WMI class (code borrowed from PowerShell team blog – to be returned when I’ve finished with it)

 

$t = [WMIClass]$class

$t.properties |

select @{Name="PName";Expression={$_.name}} -ExpandProperty Qualifiers |

where {$_.Name -eq "key"} |

foreach {"The key for the $class class is $($_.Pname)"}

 

Now I wanted to add the namespace so I tried this

PS> $namespace="root\cimv2"
PS> $class="Win32_Process"
PS> [wmiclass]"\\.\$namespace:$class"
Cannot convert value "\\.\Win32_Process" to type "System.Management.ManagementClass". Error: "Invalid namespace "
At line:1 char:11
+ [wmiclass] <<<< "\\.\$namespace:$class"
    + CategoryInfo          : NotSpecified: (:) [], RuntimeException
    + FullyQualifiedErrorId : RuntimeException

 

Huh – of course root\cimv2 is valid

But its not a WMI problem its a string substitution problem

because

PS> $target = "$namespace:$class"
PS> $target
Win32_Process

Oh – no namespace

Its because of the colon

The way we get round it is to escape the : using a backtick `

[wmiclass]\\.\$namespace`:$class

Which works

Just a little WMI quirk to be aware of

Leave a Reply