Tuesday, January 8, 2013

Using for in the world Of Powershell and WbemScripting

In the pervious post I pointed out that one way to enumerate though the object collection inside Powershell and WbemScripting is a for loop.  Looks like this:

$Locator = new-Object -comObject "WbemScripting.SWbemLocator"
$svc = $Locator.ConnectServer(".", "root\cimv2")
$ob = $svc.Get("Win32_Process")
$objs = $ob.Instances_(0)
for($x=0;$x -lt $objs.Count;$x++)
{
        $mo = $objs.ItemIndex($x)
}

Up until recently, this was something eveyone wished for.  And it is finally here. Sadly, there is no index on the propertycollection so, you still have to use a foreach loop to polish off the routine.



for($x=0;$x -lt $objs.Count;$x++)
{
     $mo = $objs.ItemIndex($x)
     foreach($prop in $obj.Properties_)
     {

     }
}

The one nice thing about Powershell is you don't have to work for the property values. These are automatically turned into strings for you.

I like that.

The next post will cover enumerators.

No comments:

Post a Comment