PowerShell script that turns off the PC at 12 midnight

1 minute reading time (254 words)

Here's a PowerShell script that turns off the PC at 12 midnight every day but warns the user first and prompts them if they want to delay for user input in minutes:

# Set the shutdown time
$shutdownTime = "12:00 AM"

# Calculate the delay time
$delayTime = New-TimeSpan -Minutes (Read-Host "Enter delay time in minutes")

# Calculate the shutdown time
$shutdownDateTime = Get-Date $shutdownTime
$shutdownDateTime = $shutdownDateTime.Add($delayTime)

# Calculate the time remaining until shutdown
$timeRemaining = ($shutdownDateTime - (Get-Date)).ToString("hh\:mm\:ss")

# Display the warning message
Write-Host "Your computer will shut down in $timeRemaining. Press any key to delay for $delayTime or CTRL+C to cancel."

# Wait for the user to respond
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

# Delay the shutdown
Start-Sleep -Seconds ($delayTime).TotalSeconds

# Shutdown the computer

 To set the script to run automatically at startup, you can create a scheduled task with the following steps:

  1. Open Task Scheduler.
  2. Click on "Create Task" in the right-hand pane.
  3. Give the task a name and description.
  4. Under the "Security Options" section, select "Run whether user is logged on or not" and "Run with highest privileges".
  5. Under the "Triggers" section, click "New" and select "Daily". Set the start time to be a few minutes before midnight and set it to repeat every day.
  6. Under the "Actions" section, click "New" and select "Start a program". Enter the path to the PowerShell executable (usually C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe) and the path to the script file.
  7. Under the "Settings" section, make sure "Allow task to be run on demand" and "Stop the task if it runs longer than" are checked.
  8. Click "OK" to save the task.

Font size: +
Report Print
Stay Informed

When you subscribe to the blog, we will send you an e-mail when there are new updates on the site so you wouldn't miss them.

By accepting you will be accessing a service provided by a third-party external to https://www.klokur.com/