Thursday, February 24, 2011

Check for logon sessions before restarting

This script will return the number of Citrix sessions for a given server (total, not active or disconnected) using WMI and determine whether it is ok to restart the server:

On Error Resume Next

Dim strComputer, UserName, Password, SWBemlocator, objWMIService, objItem, colItems, sSessions

Dim oWSH : Set oWSH = CreateObject("WScript.Shell")

strComputer = "servername"
UserName = ""
Password = ""
Set SWBemlocator = CreateObject("WbemScripting.SWbemLocator")
Set objWMIService = SWBemlocator.ConnectServer(strComputer,"root\citrix",UserName,Password)
Set colItems = objWMIService.ExecQuery("Select * from MetaFrame_Server",,48)
For Each objItem in colItems
If objItem.NumberOfSessions <>
oWSH.LogEvent 0, "Number Of Sessions: " & objItem.NumberOfSessions & ".This is the default number, restarting now..."
ShutDown
Else
sSessions = objItem.NumberOfSessions - 3
oWSH.LogEvent 4, "Number Of users still logged on: " & sSessions & ". Cancelling the restart."
End If
Next

Wscript.Quit

Sub ShutDown
Dim nLogOff, nReboot, nForceLogOff, nForceReboot, nPowerDown, nForcePowerDown, colOS, oOperatingSystem

nLogOff=0
nReboot=2
nForceLogOff=4
nForceReboot=6
nPowerDown=8
nForcePowerDown=12

Set colOS = GetObject("winmgmts:{(Shutdown)}").ExecQuery("Select * from Win32_OperatingSystem")

For Each oOperatingSystem in colOS
oOperatingSystem.Win32Shutdown(nForceReboot)
Next

End Sub


Note that username and password can be left blank when the script is run locally. I schedule the script to run once per week using the AT command.

Mitch

No comments:

Post a Comment