I know there’s a lot of confusion, with some folks, around WMI in PowerShell.
For example, this is the first type of WMI usage in PoSH that most folks saw:
$wmi = Get-WMIObject Win32_OperatingSystem
$wmi.ServicePackMajorVersion
Cool enough. Of course, in this example, you’re only ever going to get one instance of a WMI class back; with other classes, you might be multiple instances, and so you’d write a little foreach loop, perhaps, to spin throught hem all. But then RC2 came out with an all-new way of working with WMI: The WMI type adapter or type accelerator. Now you could do something like this:
[WMI]’\\Server2\root\cimv2:Win32_Process.Handle=”0″‘
This is a kinda strange-looking syntax if you’re coming from the VBScript world, and it essentially means, “Go to Server2. Connect to the root\cimv2 WMI namespace, and get the instance of the Win32_Process class where the Handle property is 0.” Using this particular syntax requires you to specify a WMI “query” that returns exactly one instance, not a collection. I’m not a big fan of this syntax, but only because… well, I’m lazy. I know my VBScript syntax, and this ain’t it. I’ll tell you though, I can think of a few times in VBScript where I could have really used a WMI syntax this concise. However, in VBScript I might have executed a query like this:
SELECT * FROM Win32_Process WHERE Handle = ‘0’
And you know what? I can use that in PowerShell, too:
$process = Get-WMIObject -query “SELECT * FROM Win32_Process WHERE Handle = ‘0’”
Of course, in PowerShell it’s easier to run that agains a remote computer:
$process = Get-WMIObject -query “SELECT * FROM Win32_Process WHERE Handle = ‘0’” -computer Server2
A benefit of this technique – using Get-WMIObject, that is – is that the query will always return a collection. In this example, the collection would only have one instance it it, but that’s okay: The fact that it’s a collection means you’ll deal with it the same no matter how many instances it contains.
So does PowerShell need these different ways of accessing WMI? Well, it doesn’t hurt. You don’t have to learn them all; learn whichever one you like. But if you were to ask the guys writing Exchange Server 2007, or System Center Operations Manager 2007, I bet they love having such flexible access to WMI.
And you know… I can see the allure. Over time I’ll memorize this syntax the same way I memorized my current VBScript-centric syntax, and I’ll come to wonder how I lived without it.