Tuesday, October 11, 2011

OT: Chatting with Windows shell (VBScript)

Just a short memo on how to use WMI (Windows Management Instrumentation) and VBScript to simplify some administration tasks.

Rebooting remote machine (have to have privileges to WMI on the remote host):
Sub Reboot(host)
On Error Resume Next
    Set wmi = GetObject("winmgmts:{(Shutdown)}\\" & host & "\root\cimv2")
    If Err.Number <> 0 Then
        Exit Sub
    End If
    Set osList = wmi.ExecQuery("SELECT * FROM Win32_OperatingSystem")
 
    For Each os In osList
        os.Reboot()
    Next
End Sub

Checking host availability:
Sub Ping(host)
    Set pingStatus = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery("SELECT * FROM Win32_PingStatus WHERE address = '" & host & "'")
    For Each pingReplay In pingStatus
       If pingReplay.StatusCode = 0 Then
            WScript.Echo "Response: OK [Time (ms)=" & pingReplay.ResponseTime & "/TTL (ms)=" & pingReplay.ResponseTimeToLive & "]"
       Else
            WScript.Echo "No response from host '" & host & "'"
       End If
    Next
End Sub

Mounting network resources:
Sub Mount(folder)
On Error Resume Next
    Set NetworkObj = CreateObject("WScript.Network")
    Set ShellObj   = CreateObject("WScript.Shell")
    NetworkObj.MapNetworkDrive "X:", folder, true', "user", "pass"
    If Err.Number = 0 Then
        ShellObj.LogEvent 0, "Network resource '" & folder & "' mounted"
    Else
        WScript.Echo "Failed (Status code: " & Err.Number & ")"
    End If
End Sub