Automating PC Shutdown with PowerShell

June 23, 2024Share
blog picture -Automating PC Shutdown with PowerShell

In the realm of system administration and everyday computer use, automating routine tasks can save time and ensure systems run smoothly. One common task is shutting down your PC at night. Rather than staying up late or waking up just to turn off your computer, you can use a simple PowerShell script to handle this automatically. This blog post explains a straightforward PowerShell script to achieve this.

The Script

Here's a breakdown of the PowerShell script designed to shut down your PC automatically after a set duration:

$startTime = Get-Date
$endTime = $startTime.AddHours(0.3)
$allowShutdown = $false

while ((Get-Date) -lt $endTime) {
Write-Host "Working..."
Start-Sleep -Seconds 60 # Sleep for 1 minute

if ((Get-Date) -ge $endTime) {
$allowShutdown = $true
}
}

# Check if shutdown is allowed
if ($allowShutdown -eq $true) {
Stop-Computer -Force
} else {
Write-Host "Shutdown is not allowed."
}

Tags: Tips, Github, Step-by-Step Guide