Wednesday, April 3, 2013
Get-WMIObject To be or not to be -- a collection or an object
Consider this code:
$mystr = ""
$ws = new-object -comobject WScript.Shell
$path = $ws.CurrentDirectory + "\Win32_Process.csv"
$fso = new-object -comobject Scripting.FileSystemObject
$txtstream = $fso.OpenTextFile($path, 2, $true, -2)
$moc = Get-WMIObject -namespace root\cimv2 -class Win32_Process
$mocEnum = $moc.GetType().InvokeMember('GetEnumerator', 'InvokeMethod',$Null, $moc, $Null)
while($mocEnum.MoveNext())
{
$obj = $mocEnum.Current
foreach($prop in $obj.Properties)
{
if($mystr -ne "")
{
$mystr += ","
}
$mystr += $prop.Name
}
$txtstream.WriteLine($mystr)
$mystr = ""
break
}
$mocEnum.Reset()
while($mocEnum.MoveNext())
{
$obj = $mocEnum.Current
foreach($prop in $obj.Properties)
{
if($mystr -ne "")
{
$mystr += ","
}
$tstr = '"'
$tstr += $prop.value
$tstr += '"'
$mystr += $tstr
}
$txtstream.WriteLine($mystr)
$mystr = ""
}
As it stands, this code works well to create a csv file. And, yes, you can do the same using the PSObject. The problem is, the code assumes the Get-WMIObject will return a collection of objects and in some cases it will not.
Exception calling "InvokeMember" with "5" argument(s): "Method 'System.Management.ManagementObject.GetEnumerator' not found."
At C:\Users\Administrator\Desktop\Test.ps1:2 char:39
+ $mocEnum = $moc.GetType().InvokeMember <<<< ('GetEnumerator', 'InvokeMethod',$Null, $moc, $Null)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
You cannot call a method on a null-valued expression.
At C:\Users\Administrator\Desktop\Test.ps1:3 char:24
+ while($mocEnum.MoveNext <<<< ())
+ CategoryInfo : InvalidOperation: (MoveNext:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
And, by the way, the code works fine using foreach enumerations of the objects.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment