Friday, November 7, 2008

Error Handling 101 for Scripts

Here's a small but useful tip for all you folks writing scripts out there in VBScript (adapt as you wish for Kixtart, Powershell, or whatever):  Build in some error handling.

Instead of doing this all the time...

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_SystemSlot")
Do this...

strComputer = "."
On Error Resume Next
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
If err.Number <> 0 Then
    wscript.echo "error (" & err.Number & "): failed to connect to wmi instance"
    wscript.quit
End If
Set colItems = objWMIService.ExecQuery("Select * from Win32_SystemSlot")

Make sure you get the object first, then get to work querying what's inside of it.  It's a good habit to adopt.

No comments: