PowerShell has lot of different layers of security that prevent malicious scripts and commands from being executed. For example, by default you cannot run a script that you’ve downloaded from the internet unless you change the PowerShell execution policy. Another security measures prevents you from executing a script by double-clicking it. You can’t associate PS1 scripts with PowerShell and the only way to run a script is to right-click it and select the run option. Double-clicking it will open it in Notepad. This is great for a security measure but annoying if you want a PowerShell script to execute when a scheduled task is run. The work around is simple. You can use a batch script to auto-run PowerShell scripts.
The following is the batch script you need in order to auto-run PowerShell scripts on Windows 10. Each PowerShell script will need its own Batch Script.
@ECHO OFF PowerShell.exe -Command "Path to script" PAUSE
Replace “Path to script” with the actual path to the PowerShell script you want to execute. Consider the following example;
@ECHO OFF PowerShell.exe -Command "C:Reminder-ScriptsMilkBuy-Milk.ps1" PAUSE
Open Notepad and paste the script in it. Save the file with the .bat extension.
RECOMMENDED FOR YOU
What this batch files does is that it opens PowerShell and then runs the script that you’ve pointed it to. You still cannot double-click a PowerShell script on your desktop and have it automatically run in PowerShell. The current file will open a Command Prompt window and it will show a ‘Press any key to continue’ message. When you press a key, only then will the PowerShell script run. If you prefer the script run without you having to intervene, edit the above script and remove the ‘PAUSE’ line. It should look like this;
@ECHO OFF PowerShell.exe -Command "Path to script"
Task Scheduler PowerShell Scripts
We’re assuming you want to automatically run a PowerShell script as an action to a scheduled task. To accomplish this, you need to first create a corresponding Batch script, as shown above, to run the PowerShell script. Next, when you create a scheduled task, select the Batch script under the Action it should take in response to a trigger. This will, in effect, run the PowerShell script.
We’ve used Task Scheduler as an example here but if you’re using any other automation app, you will still need to call the Batch script. The only exception is if the automation app you’re using can open PowerShell and then point it to the PowerShell script.