Saturday, May 13, 2006

Goodbye Array... hello Disconnected DataSet!

I've always hated working with Arrays in VBScript... they're fiddly at the best of times. And if you ever have to sort the data in an array (let alone a multidimensional one), you're pretty much screwed. Enter the Disconnected DataSet.

Instead of building an array and stuffing data into it, you can create an in memory database using ADO that only exists while the script executes. I'm sure from an application perspective there are tons of risks associated with using such a technique to actually talk back to real database at some point, but for administrative scripting, it's a godsend.

So say you wanted to query all the services on a machine using WMI, and list them in order of the state they were in as opposed to the alphabetical order of the service name (which is the order WMI would return the query in). You would simply:

Const adVarChar = 200
Const MaxCharacters = 255
Set DataList = CreateObject("ADOR.Recordset")
DataList.Fields.Append "ServiceName", adVarChar, MaxCharacters
DataList.Fields.Append "ServiceState", adVarChar, MaxCharacters
DataList.Open
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer& "\root\cimv2")
Set colServices = objWMIService.ExecQuery _
("SELECT * FROM Win32_Service")
For Each Service in colServices
DataList.AddNew
DataList("ServiceName") = Service.Name
DataList("ServiceState") = Service.State
DataList.Update
Next
DataList.Sort = "ServiceState"
DataList.MoveFirst
Do Until DataList.EOF
Wscript.Echo DataList.Fields.Item("ServiceName") _
& vbTab & DataList.Fields.Item("ServiceState")
DataList.MoveNext
Loop


Here is the link to where that code came from... I am sure I will be using this technique a lot from now on.

No comments: