I wanted to create a Scheduled Task on my Citrix Servers to have the reboot every other night.

The idea is that half of the servers will reboot in a night and the other half the following night.

The TSSHUTDN tool is handy since it can issue a warning to logged on users, log them out after a certain period and finally issue the reboot.

Since I needed to add a scheduled task to many servers I wanted to do this with a script.

WMI Exposes the Win32_ScheduledJob Class and it’s Create Method.

The parameters, especially StartTime, are constructed very odly and I can never remember them.

So I wrote a very simple wrapper in PowerShell to make it a little easier for the next time:

powershell Download
# Weekdays
$Mo = 1 ; $Tu = 2 ; $We = 4 ; $Th = 8 ; $Fr = 16 ; $Sa = 32 ; $Su = 64

# Get Time Bias
$Bias = $Bias = "{0:D3}" -f [int][System.TimeZoneInfo]::Local.BaseUtcOffset.TotalMinutes

# Get Correct Sign
if ($Bias -gt 0) { $Sign = "+" } else { $Sign ="-" }

# Fill in these parameters
$Command = "tsshutdn.exe 900 /reboot /delay:300 /v"
# Time in HHMMSS (24h)
$Time = "020000"
$Repeat = $true

# if $Repeat = False then $Days must be 0 else combine days with -bor
$Days = $Mo -bor $We -bor $Fr
# End fill in

# Compose StartTime String
$StartTime = [System.String]::Concat("********", $Time, ".000000", $Sign, $Bias)

# Add the task, note that DaysOfMonth and InteractWithDesktop (last 2 params) are not used
([wmiclass]"Win32_ScheduledJob").Create($Command, $StartTime, $Repeat, $Days, $null, $false)