Difference while working with WMI via VBScript and PowerShell
I have a test Windows XP SP3 clean install with power shell. It's a very strange difference if i access WMI from PowerShell and from VBScript. From powershell:
Get-WmiObject 开发者_运维技巧'Win32_OperatingSystem" | select Caption
This correctly displays "Windows XP Professional". And same code written as VBScript:
WScript.Echo( GetObject( "winmgmts:Win32_OperatingSystem" ).Caption )
Displays "null" O_O. Why this happens?
Here is the VBScript equivalent:
Set wmi = GetObject("winmgmts:")
Set objSet = wmi.InstancesOf("Win32_OperatingSystem")
For Each obj in objSet
WScript.Echo obj.Caption
Exit For
Next
Although there is only one Operating System, a WMI query always returns a list.
Ok, now, the difference - Using the Get-WmiObject
cmdlet, since there is only one operation system, you get the object directly rather than a list when you do Get-WmiObject "Win32_OperatingSystem"
( use GetType to see that this is actually of type System.Management.ManagementObject
)
Since there will be multiple processes, get-wmiobject win32_process
would give a array. ( use GetType to see that this is of type System.Object[]
The following would not give any output:
(get-wmiobject win32_process).Caption
Whereas the below would:
(get-wmiobject win32_process)[0].Caption
精彩评论