Reboot Session Host Server automatically

I recommend rebooting your terminal server at lease once a week to clear up your memmory. Often your customer would like to be advertised before the servers are rebooted. I created below script which queries the connection broker for remote dekstop session host servers. For each session host server it sends a message to each logged on user. Waits 5 minutes and then reboots the server.

Import-Module RemoteDesktop
$connectionbroker = "hostname.fqdn.com"
$collectionName = "Desktop"
$MessageSubject = "Reboot Schedule"
$MessageBody = "You have entered the daily reboot schedule. Please save your work. You will be logged off automatically within 5 minutes"

$SessionHosts = Get-RDSessionHost -CollectionName $collectionName -ConnectionBroker $connectionbroker

#Send Message to Users that they will be logged out

foreach ($Hosts in $SessionHosts ) {

echo $Hosts.SessionHost #debugUse

$RDSessions = Get-RDUserSession -CollectionName $collectionName -ConnectionBroker $connectionbroker | where {<#$_.SessionState -eq "STATE_DISCONNECTED" -and #> $_.HostServer -eq $Hosts.SessionHost}

Foreach ($RDSession in $RDSessions) {

Send-RdUSerMessage -MessageTitle $MessageSubject -MessageBody $MessageBody -HostServer $Hosts.SessionHost -UnifiedSessionID $RDsession.SessionID

}

}

#Timedelay before logging user off
Start-Sleep -s 300

#Log Users off and reboot

foreach ($Hosts in $SessionHosts ) {

#echo $Hosts.SessionHost #debugUse

$RDSessions = Get-RDUserSession -CollectionName $collectionName -ConnectionBroker $connectionbroker | where {<#$_.SessionState -eq "STATE_DISCONNECTED" -and #> $_.HostServer -eq $Hosts.SessionHost}

Foreach ($RDSession in $RDSessions) {
Invoke-RDUserLogoff -UnifiedSessionID $RDSession.SessionId -HostServer $RDSession.HostServer -Force
}

Restart-Computer -Force -ComputerName $Hosts.SessionHost
}

Was this article helpful 1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)

Loading...