I'm trying to schedule a Powershell script to run from Windows Task scheduler. The script works fine when run manually from a PS window. When I make it the action of a scheduled task, however, two issues arise:
I have confirmed that the task is set up with correct user permissions.
I have confirmed in Event Viewer that the trigger event has occurred and been logged correctly.
The action for the task is:
"Start a Program" Program/script:
powershell
Arguments:-File "C:\Users\<username>\Desktop\script.ps1"
Here's the relevant parts of my script:
Start-Sleep -Seconds 2
If (!(Test-NetConnection -ComputerName www.example.com -InformationLevel "Quiet")) {
#The code in here won't affect basic execution, since during testing this If condition evaluates to False
} Else {
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[System.Windows.Forms.MessageBox]::Show("You're good to go!" , "Info" , 3)
Exit
}
I would expect that when I test this task, I should just get the messagebox popping up, then the task should stop running. Neither of these occur, and I really have no idea why.
The issue was that "running scripts is disabled on this system."
about_Execution_Policies https://go.microsoft.com/fwlink/?LinkID=135170 SecurityError: ParentContainsErrorRecordException | UnauthorizedAccess
The solution was to add -ExecutionPolicy Bypass
to the task arguments.
(There is now a separate issue of a console window appearing on the screen that -WindowStyle Hidden
doesn't solve, but there's lots of similar documentation for that problem, and I'll post a new question if I can't find a suitable solution).