Tuesday, June 21, 2005

WMI Scripting with MSH

If MSH is to become the next best scripting thing, then its got to enable a number of different scenarios. One use of MSH is to do WMI scripting - using MSH get access to WMI objects, properties and methods.

I started by looking at the [truly amazing!] TechNet script centre, which has a large number of existing WMI scripts. As it turns out, it's surprisingly easy to write WMI scripts, once you master the differences between VBscript and Monad!

The first script I tackled is at: http://www.microsoft.com/technet/scriptcenter/scripts/desktop/logon/dmlgv b02.mspx

'-----------
strComputer = "atl-ws-o1"
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colComputer = objWMIService.ExecQuery _ ("Select * from Win32_ComputerSystem")
For Each objComputer in colComputer
Wscript.Echo "Logged-on user: " & objComputer.UserName
Next
'------------

In MSH this is just 3 lines:

$strComputer = "kapoho61"
$colComputer = get-wmiObject win32_computersystem -comp $strComputer
foreach ($comp in $colcomputer){"Logged-on user: " + $comp.username}

8 lines into 3 - not bad!

My second attempt was to reproduce http://www.microsoft.com/technet/scriptcenter/scripts/desktop/logon/dmlgv b01.mspx

'-------------- strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_LogonSession")
For Each objItem in colItems
Wscript.Echo "Authentication Package: " & objItem.AuthenticationPackage
Wscript.Echo "Logon ID: " & objItem.LogonId
Wscript.Echo "Logon Type: " & objItem.LogonType
Wscript.Echo "Start Time: " & objItem.StartTime
Wscript.Echo
Next
'--------------

Becomes:

$strComputer = "kapoho61"
$colComputer = get-wmiObject win32_LogonSession -comp $strComputer
foreach ($comp in $colcomputer) {"Authentication Package: " + comp.AuthencationPackage
"Login ID: " + $comp.LogonId
"Login Type: " + =$comp.LogonType
"Start Time: " + $comp.StartTime}

11 lines into 6.

All in all - this WMI scripting stuff looks to be easy in MSH. What would be really cool now is for someone to create a msh-scriptomatic.hta (to mimic the scroptomatic.hta currently available). I just wish I was better at HTAs.

MSH Rocks!!

(submitted by email - apologies for layout!)

No comments: