Tuesday, January 8, 2013

Powershell - WbemScripting.SWbemLocator returns a ManagementObject on single instances

Okay, for all of you out there who would love some relief from the misery of leaning Powershell by the seat of your pants and are tired of crashing and burning, let's begin with solution #1.

You have been given the task of writing a powershell script that uses WbemScripting.SWbemLocator.


$Locator = new-Object -comObject "WbemScripting.SWbemLocator"
$svc = $Locator.ConnectServer(".", "root\cimv2")
$ob = $svc.Get("win32_bios")
$objs = $ob.Instances_(0)

So at this point you want to enumerate through the object collection.  There are two ways of doing this, right?

foreach($obj in $objs)
{


}

and

for($x=0;$x -lt $objs.Count;$x++)
{

}

Acturally, there are about six more. But, none will work.

What?

Yep, none will work.  Here's why.  When Powershell sees on one iteration of an object which in this case, unless you have more than one BIOS on your board, it sees only one, an SWbemObject is returned and not a SWbemObjectSet.

You can easily deal with this situation like this:

if($objs.Count -gt 0)
{  
    foreach($obj in $objs)
    {
        foreach($prop in $obj.Properties_)
        {
   
        }
    }
}
else
{
     $obj = $objs
     foreach($prop in $obj.Properties_)
     {

     }
}

And that is your first subscription for pain relief.

No comments:

Post a Comment