Accessing Individual WMI Instances

by Jan 3, 2009

You always get back all instances of a given WMI class when using Get-WMIObject. However, what if you just wanted to get a specific instance? Or you just wanted to find out how much space is left on drive C:? The next line gives you all drives:

Get-WMIObject Win32_LogicalDisk | Format-Table Name, FreeSpace

The trick is to use casting and WMI paths. The following line will provide specifically the C: drive:

[wmi]'Win32_LogicalDisk="C:"' | Format-Table Name, Freespace -autosize

To simply get the free bytes, use this:

([wmi]'Win32_LogicalDisk="C:"').FreeSpace

What happens here is a simple conversion. You specify text, then you ask PowerShell to convert it to a WMI object using [wmi], which is actually is a type accelerator, a shortcut. This is a way to find out the real .NET type it refers to:

[wmi].FullName

Of course, PowerShell cannot convert any string to a WMI object. You will need to specify the exact WMI object path, which is unique for each WMI object and contains the class name and so called key properties. Here is how you find out the object path for a Service:

Get-WmiObject Win32_Service | Format-Table Name, __Path -wrap

You can omit the PC name and WMI namespace for local objects in the standard WMI namespace. So to access a given Service directly, do this:

[wmi]'Win32_Service="WSearch"' | Format-List *

Why not use Get-Service? You could, but WMI is returning a lot more information about a service:

Get-Service WSearch | Format-List *