TL;DR: How to run a script on a schedule with Task Scheduler and PowerShell
The fix only. No explanation, no diagnosis. Read the full article if any of this does not match what you are seeing.
- With the script in an administrators-only folder such as
C:\Scripts, in an elevated PowerShell window build and register the task (this one runs daily at 02:00 as SYSTEM):
$action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-NoProfile -ExecutionPolicy Bypass -File "C:\Scripts\Nightly.ps1"' -WorkingDirectory 'C:\Scripts'
$trigger = New-ScheduledTaskTrigger -Daily -At 2:00AM
$principal = New-ScheduledTaskPrincipal -UserId 'NT AUTHORITY\SYSTEM' -LogonType ServiceAccount -RunLevel Highest
$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -ExecutionTimeLimit (New-TimeSpan -Hours 1)
Register-ScheduledTask -TaskName 'Nightly' -Action $action -Trigger $trigger -Principal $principal -Settings $settings- Run it once now and check the result:
Start-ScheduledTask -TaskName 'Nightly'
Get-ScheduledTaskInfo -TaskName 'Nightly'- Read
LastTaskResult: 0 is success, 0x41301 means still running, anything else: check your script's log and the TaskScheduler Operational log. To remove the task:Unregister-ScheduledTask -TaskName 'Nightly' -Confirm:$false
Anyone who can edit the script can run code as the task's account, so never leave it where ordinary users can write. Make the script log to its own file.