Powershell – That torrid vbScript affair – Part 6

Powershell

“…today Powershell connected to my Outlook libraries and pulled down my email objects.  I couldn’t explain away all the WENDS or FOR any reason could I determine what would happen NEXT.  My options are look DIM. I had better GET-PROCESS CSCRIPT | STOP-PROCESS and GET-CHILDITEM –recurse –include *.vbs | REMOVE-OBJECT before Powershell does a REMOVE-ITEM on me… This has gone far enough…I love Powershell too much.”

So we will take one last dip into the land of vbScript.  One tiny view of the loopiness aspect of it.

Earlier we mentioned the “FOR NEXT” loop and how it translated in Powershell.  What is interesting and nice (and VERY important to know) is that vbScript ALSO has a FOREACH loop to pass through a collection of objects.   It functions almost identical to Powershell.

So here’s a typical “FOREACH” loop in vbScript that will list all the Logical Drives as well as their Free Space and Size on a computer.

On Error Resume Next

strComputer = "."
Set objWMIService = GetObject("winmgmts:" –
    & "{impersonationLevel=impersonate}!\" & strComputer & "rootcimv2")

Set colItems = objWMIService.ExecQuery –
    ("Select * from Win32-LogicalDisk")

For Each objItem in colItems
    Wscript.Echo "Computer: " & strComputer
    Wscript.Echo "Drive Letter: " & objitem.Name
    Wscript.Echo "Size: " & objItem.Size
    Wscript.Echo "Free Space: " & objItem.FreeSpace
    WScript.Echo
Next

As convoluted as that appears, really all the first series of lines

Set objWMIService = GetObject("winmgmts:" –
    & "{impersonationLevel=impersonate}!\" & strComputer & "rootcimv2")

Set colItems = objWMIService.ExecQuery –
    ("Select * from Win32-LogicalDisk")

is just THIS in Powershell

$strcomputer=’localhost’ 

$colItems=GET-WMIOBJECT –query “Select * from Win32-LogicalDisk” –computername $strcomputer

This is one of the ways where Powershell beats vbScript.  It has a much more integrated way of handling and querying WMI.

So looking at the FOREACH loop in vbScript which is

For Each objItem in colItems
    Wscript.Echo "Computer: " & strComputer
    Wscript.Echo "Drive Letter: " & objitem.Name
    Wscript.Echo "Size: " & objItem.Size
    Wscript.Echo "Free Space: " & objItem.FreeSpace
    WScript.Echo
Next

 

In Powershell this SAME loop looks like this to manage the Objects

FOREACH ( $objitem in $colitems) {
     WRITE-HOST “Computer: $strComputer”
     WRITE-HOST “Drive Letter: $objitem.Name”
     WRITE-HOST “Size: $objitem.Size”
     WRITE-HOST “Free Space: $objitem.Freespace”
}

So really, the two Scripting languages in the way they handle loops are VERY similiar except for minor details in Syntax.  In knowing this, you should be able to build new Powershell Scripts while leveraging the established Power of past vbScript Masters.

Next time we’ll touch just a bit on some tiny details on Synatx and end this Torrid affair.

The Power of Shell is in YOU

Sean
the Energized Tech

Leave a Reply