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 Stop-Computer
To set the script to run automatically at startup, you can create a scheduled task with the following steps:
- Open Task Scheduler.
- Click on "Create Task" in the right-hand pane.
- Give the task a name and description.
- Under the "Security Options" section, select "Run whether user is logged on or not" and "Run with highest privileges".
- 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.
- 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.
- Under the "Settings" section, make sure "Allow task to be run on demand" and "Stop the task if it runs longer than" are checked.
- Click "OK" to save the task.