Skip to content

Instantly share code, notes, and snippets.

@NiceRath
Last active October 5, 2024 10:09
Show Gist options
  • Save NiceRath/f01b38cbb366cd09760db7bd791c49cf to your computer and use it in GitHub Desktop.
Save NiceRath/f01b38cbb366cd09760db7bd791c49cf to your computer and use it in GitHub Desktop.
Windows RDS - Script to gracefully reboot the server (notify users)
# Task Scheduler
# General
# Use local service-user of SYSTEM
# Enable 'Run whether user is logged in or not'
# Enable 'Do not store password'
# Enable 'Run with highest privileges'
#
# Action
# Program: C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe
# Arguments: -File C:\scripts\GracefulReboot.ps1
# NOTE: you may want to change the 'MessageTitle' and 'MessageBody' of the user-notifications
$date = Get-Date -format yyyy-MM-dd
$logFile = "C:\logs\auto_reboot.log"
Write-Output "-------------------------"$date"-------------------------" >> $logFile
#getting all users that are logged on locally
$quserResult = quser 2>&1
$quserRegex = $quserResult | ForEach-Object -Process { $_ -replace '\s{2,}',',' }
$quserObject = $quserRegex | ConvertFrom-Csv
#write info messages to all logged on users
foreach ($user in $quserObject){
Send-RDUserMessage -HostServer localhost -UnifiedSessionID $user.ID -MessageTitle "Administrator" -MessageBody "Bitte schließe und speichere offene Dokumente/Programme. Du wirst in 10 Minuten abgemeldet. Eine Wieder-Anmeldung ist nach 5 Minuten möglich. (automatische Nachricht)"
}
#wait 9 minutes
Start-Sleep -Seconds 540
#another message to all logged on users
foreach ($user in $quserObject){
Send-RDUserMessage -HostServer localhost -UnifiedSessionID $user.ID -MessageTitle "Administrator" -MessageBody "Du wirst in 1 Minute abgemeldet. Eine Wieder-Anmeldung ist nach 5 Minuten möglich. (automatische Nachricht)"
}
#wait 1 minute
Start-Sleep -Seconds 60
#log off all users
foreach ($user in $quserObject){
$username = $user.USERNAME.Substring(1)
Write-Output "Logging off user '$username'"
Invoke-RDUserLogoff -HostServer localhost -UnifiedSessionID $user.ID -Force
} 3>&1 2>&1 >> $logFile
#wait for clean logoff
Start-Sleep -Seconds 60
#rebooting server
Write-Output "Rebooting server!" >> $logFile
Restart-Computer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment