Running powershell scripts in the Windows Task Scheduler

2022-08-06

I recently found myself needing to automate the tedious task of parsing production log files. The client does no use any kind of log management software (for example, greylogs). Instead they log everything to files on the server's drive.

After releasing a new feature, we want to see if any of the client's customers are getting any hits on the new feature. This meant we needed to check the logs about every day (due to logging policy). So I created a powershell script that would copy the logs locally, grep them, and throw the grep results into a text file that I could read at the end of every week.

I ended up running into an issue where the Task Scheduler reported the powershell script exiting with the code 2147942401. After some head banging, I found that the issue was caused by powershell's execution policy.

By default the Execution Policy is set as follows:

PS C:\> Get-ExecutionPolicy -List

        Scope ExecutionPolicy
        ----- ---------------
MachinePolicy       Undefined
   UserPolicy       Undefined
      Process       Undefined
  CurrentUser       Undefined
 LocalMachine    RemoteSigned

This means that powershell.exe is not allowed to run scripts unless they've been remotely signed.

Luckily you can override this behaviour by specifying the execution policy. In the task's action, under Add Arguments, you can set the parameters

-NoProfile -NoLogo -NonInteractive -ExecutionPolicy Bypass -File "path/to/file"

The important bit is the -ExecutionPolicy Bypass, which will allow the task to run scripts.

And now I can sit back and reap the sweet sweet 5 minutes I saved from doing it manually. :D