Add Add schedule_reboot.ps1

This commit is contained in:
Ivo Oskamp 2024-11-29 11:18:25 +01:00
parent 9e5e1e9ebd
commit de83011abb

35
Add schedule_reboot.ps1 Normal file
View File

@ -0,0 +1,35 @@
# Define the reboot time
$rebootTime = "21:00"
# Get the current date and time
$currentDate = Get-Date
# Parse the reboot time into a DateTime object for today
$rebootDateTime = [datetime]::ParseExact("$($currentDate.ToString('yyyy-MM-dd')) $rebootTime", "yyyy-MM-dd HH:mm", $null)
# Check if the reboot time is in the past for today; if so, schedule it for tomorrow
if ($rebootDateTime -lt $currentDate) {
$rebootDateTime = $rebootDateTime.AddDays(1)
}
# Format the DateTime object for the task scheduler
$taskTime = $rebootDateTime.ToString("HH:mm")
# Create a scheduled task action for a forced reboot
$taskName = "ForcedReboot"
$action = New-ScheduledTaskAction -Execute "shutdown.exe" -Argument "/r /f /t 0"
# Create a trigger for the specified time
$trigger = New-ScheduledTaskTrigger -Once -At $rebootDateTime
# Configure settings to allow the task to run when no user is logged in
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable `
-RunOnlyIfIdle:$false -WakeToRun
# Set the task to run with the highest privileges and even when no user is logged in
$principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount -RunLevel Highest
# Register the task
Register-ScheduledTask -TaskName $taskName -Action $action -Trigger $trigger -Settings $settings -Principal $principal -Force
Write-Host "Scheduled reboot at $rebootDateTime, even if no user is logged in."