Search code examples
powershellwindows-task-scheduler

Scheduled Powershell won't run when triggered, won't stop running when run manually


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:

  1. When the trigger occurs, the task does not start.
  2. When I run the task manually from within Task Scheduler, an empty Powershell console window appears for a few seconds, then disappears. The Task status says "Running," and remains that way until I manually end it.

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.


Solution

  • 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).