This function uses the (legacy) VmCom API for VBScript to connect to one or more ESX servers, enumerate the VM’s currently owned by that ESX server and determine both the VM state and whether it has any current snapshots. The ‘SENDMAIL’ flag at the end is a boolean that was used to determine if the returned data was worthy of emailing out or not (i.e. if there were any current snapshots or any VM’s were powered off, suspended, etc).
Function CheckServer(strServer)
On Error Resume Next
bSendMailFlag = False
Set ConnectParams = CreateObject("VmCOM.VmConnectParams")
ConnectParams.username = "root"
ConnectParams.password = "password"
ConnectParams.hostname = strServer
Set ESXServer = CreateObject("VmCOM.VmServerCtl")
' ----- Connect to the server -----
ESXServer.Connect ConnectParams
If Err.number = 0 Then
strVMConnect = "Connected to: " & strServer & vbCrLf
Else
strVMConnect = "Error occured connecting to " & strServer & ": " & Err.Description & " (" & Err.Number & ")"
Err.Clear
bSendMailFlag = True
strVMConnect = "SENDMAIL&" & strVMConnect
CheckServer = strVMConnect
End If
' ---- Get a list of all VMs from the server ----
Set vmCollection = ESXServer.RegisteredVmNames
strVMConnect = "VMware ESX Server: " & strServer & " (Total VM's: " & vmCollection.Count & ")" & vbCrLf
j = 1
For Each vmObject in vmCollection
ConfigPath = vmCollection.Item(j)
' Connect to the VM
Set vm = CreateObject("VmCOM.VmCtl")
vm.Connect ConnectParams, ConfigPath
If Err.Number <> 0 Then
strVMConnect = strVMConnect & "Could not connect to VM " & vm.ConfigFileName & ": " & Err.Description & " (" & Err.Number & ")" & vbCrLf
Err.Clear
Else
' ----- Check state of the VM ----
Select Case vm.ExecutionState
Case 1
fVMState = "ON"
Case 2
fVMState = "OFF"
bSendMailFlag = True
Case 3
fVMState = "SUSPENDED"
bSendMailFlag = True
Case 4
fVMState = "STUCK"
bSendMailFlag = True
Case Else
fVMState = "UNKNOWN"
bSendMailFlag = True
End Select
' ---- Check if the VM has snapshots or not ----
If vm.HasSnapshot Then
strVMConnect = strVMConnect & "VM " & j & ": " & vmObject & " - State: " & fVMState & ", Snapshot(s): YES" & vbCrLf
bSendMailFlag = True
Else
strVMConnect = strVMConnect & "VM " & j & ": " & vmObject & " - State: " & fVMState & ", Snapshot(s): NO" & vbCrLf
End If
End If
j = j+1
Next
Set vm = Nothing
Set ESXServer = Nothing
Set ConnectParams = Nothing
If bSendMailFlag Then
strVMConnect = "SENDMAIL&" & strVMConnect & vbCrLf
Else
strVMConnect = "&" & strVMConnect & vbCrLf
End If
CheckServer = strVMConnect
End Function
