Skip to content

Instantly share code, notes, and snippets.

@figueroadavid
Created June 2, 2023 17:18
Show Gist options
  • Select an option

  • Save figueroadavid/ddfd7d39c3941cd9bcb515df7e91ced8 to your computer and use it in GitHub Desktop.

Select an option

Save figueroadavid/ddfd7d39c3941cd9bcb515df7e91ced8 to your computer and use it in GitHub Desktop.
Import-Module PSScheduledJob
function Set-DrainAndReboot {
[cmdletbinding()]
param(
[parameter(Mandatory)]
$ComputerName
)
$RebootScriptBlock = @'
$CitrixSessionCount = (Get-CimInstance -Namespace Root\Citrix\hdx -ClassName Citrix_Sessions ).count
$CycleCount = 0
do {
$CycleCount++
$LogEntry = '[{0}]{1} Cycle:{4} There are {2} sessions remaining on {3}' -f ([datetime]::Now), "`t", $CitrixSessionCount, $env:COMPUTERNAME, $CycleCount
$ACParams = @{
Path = 'C:\RebootMonitor.txt'
Value = $LogEntry
}
Add-Content @ACParams
Start-Sleep -Seconds 300
} until ($CitrixSessionCount -eq 0)
$LogEntry = '[{0}]{1}Rebooting {2}' -f ([datetime]::Now), "`t", $env:COMPUTERNAME
Restart-Computer -Force
'@
$Argument = '-nologo -noprofile -encodedcommand {0}' -f ([System.Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($RebootScriptBlock)))
$TaskParams = @{
Trigger = New-ScheduledTaskTrigger -At ([datetime]::Now) -Once
Principal = New-ScheduledTaskPrincipal 'NT Authority\System' -LogonType ServiceAccount -RunLevel Highest
Action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument $Argument
Description = 'Drain_and_Reboot; This script monitors the number of active Citrix Sessions, and when it reaches 0, it reboots the system'
}
$thisTask = New-ScheduledTask @TaskParams
Invoke-command -ComputerName $ComputerName -ScriptBlock {
$thisTask = Register-ScheduledTask -InputObject $using:thisTask -TaskName 'DrainAndReboot'
$thisTask.Author = '{0}\{1}' -f $env:USERDOMAIN, $env:USERNAME
$thisTask | Set-ScheduledTask
}
Invoke-command -ComputerName $ComputerName -ScriptBlock { Start-ScheduledTask -TaskName 'DrainAndReboot' }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment