Skip to content

Instantly share code, notes, and snippets.

@contactbrenton
Last active September 20, 2024 00:13
Show Gist options
  • Save contactbrenton/318af25acf4fed3fe9cc8ee05b57725f to your computer and use it in GitHub Desktop.
Save contactbrenton/318af25acf4fed3fe9cc8ee05b57725f to your computer and use it in GitHub Desktop.
Powershell script to reboot windows between 1am and 3am system time. Logic put in as a safeguard to protect against queued events.
# Restart-ComputerWithTimeCheck.ps1
# Description: This script will restart the computer using the /g option,
# but only if the current system time is between 1:00 AM and 3:00 AM.
# List of Logged-in Users and Sessions
Write-Host "======================================" -ForegroundColor Yellow
Write-Host "Logged-in Users:" -ForegroundColor White
Write-Host "--------------------------------------" -ForegroundColor Yellow
query user
Write-Host ""
Write-Host "======================================" -ForegroundColor Yellow
Write-Host "Active Sessions:" -ForegroundColor White
Write-Host "--------------------------------------" -ForegroundColor Yellow
query session
Write-Host ""
Write-Host "======================================" -ForegroundColor Yellow
Write-Host "Script Results:" -ForegroundColor White
Write-Host "--------------------------------------" -ForegroundColor Yellow
# Get the current system time
$currentHour = (Get-Date).Hour
# Check if the current time is between 1:00 AM and 3:00 AM
if ($currentHour -ge 1 -and $currentHour -lt 3) {
try {
Write-Output "System time is between 1:00 AM and 3:00 AM. Restarting the computer with /g..."
shutdown /g /t 3600
Write-Output "Restart command sent successfully."
} catch {
Write-Error "Failed to send the restart command. Error: $_"
}
} else {
Write-Output "System time is not between 1:00 AM and 3:00 AM. Script will not execute."
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment