How To Properly Schedule A Task to Run PowerShell Script

By | August 26, 2020

With more and more scripts written in PowerShell, a lot more tasks are scheduled to be run in PowerShell, instead of batch files. So it’s important to properly schedule a task that runs the PowerShell powered scripts smoothly and successfully.

To start, open Task Scheduler by clicking Start menu and typing Task Scheduler and click Create Basic Task… or Create Task… from the Actions pane.

At Action step, select Start a program and click Next.

At the next window, type PowerShell as the Program/script and the full-path of the script file as the argument. If the path includes any space, wrap the whole string up with a full quotation mark.

Click Next to finish the setup.

Why the job is failed?

The task will have no problem to run, as long as the local PowerShell execution policy is set as unrestricted. Or it will fail.

So how to prevent this from happening?

You can specify which policy to use with the switch -ExecutionPolicy, like below:

PowerShell -ExecutionPolicy Unrestricted -File "fullpathscript.ps1"

For Scheduled Tasks, put PowerShell in the Program/script box and the rest in the arguments box.

How do I hide the PowerShell window during the runtime?

By default, when the script runs it opens a PowerShell console window and closes it when the job is finished. If the job is relatively quick, it’s no big deal leaving it open but when the job takes longer to finish it’s better not so obvious.

That’s where the switch -WindowStyle comes in to play. There are 4 types of style you can choose from: Normal, Minimized, Maximized, and Hidden. Apparently, hidden is what we are after.

Put together,

PowerShell -ExecutionPolicy Unrestricted -WindowStyle Hidden -File "fullpathscript.ps1"

What about PowerShell 7?

If you have PowerShell 7 installed and want it to run your PowerShell 7 compatible script, use pwsh to launch PowerShell instead. All the switches mentioned above still apply.

The post How To Properly Schedule A Task to Run PowerShell Script appeared first on Next of Windows.