Powershell Scheduled Task
Sometimes we need to automate a procedure on the server; this task can be achieved by running a scheduled task that fires a Windows PowerShell scheduled task script.
The first thing we need to do is write the Powershell Script; you can if you wanted to, write the script in notepad and then save it as a .ps1 file and that's it, the script is written.
Or you can open Windows PowerShell ISE by following the steps below, which I have done on Windows 10:
- Open Start
- Search for Windows PowerShell ISE
- Click on File
- Select New to create a new empty .ps1 file.
If all goes to plan, you should have something looking like the image below.What we want to achieve in this blog is to ping a webpage every day at 2 am. There are many reasons why we may want to do this, such as to ping the website to ensure it up and running.
To save the script, we click 'File', 'Save As' and save the file in our chosen location.
PowerShell Scheduled Task Windows Server
Now that you have saved the .ps1 file, we need to create a scheduled task on the server.
The process has many steps which are listed below:
- Click on search
- Type in Task Scheduler
- Then click on Task Scheduler
Below is how it looks on my desktop.
Once done, we need to create the scheduled task, to achieve this either click on Action > Create Task, or on the right of the 'task scheduler' click on Create Task.
On the pop-up, give the Task a name, make it unique as you may one day have many scheduled tasks and check 'Run whether user is logged on or not' and tick 'Do not store password'.
Once you have given the task a name, click on Triggers and new, here we set the date and time we want the job to run.
Now click on the 'Action Tab', now I remember many many years ago, I got this wrong, and it took a couple of hours for me to work out what I missed.
After clicking on the 'Action Tab' click 'New' and enter the following:
- Program Script: Enter Powershell.exe
- Add arguments: Enter -ExecutionPolicy Bypass d:\test.ps1 and add the path to the .ps1 file you created earlier. DO NOT forget the - in front of ExecutionPolicy, or you may spend hours like me trying to work out why it would not work :(
Now click, OK, and you should have the following.
Click OK and then select the Conditions tab, and tick the box 'Wake the computer to run this task.'You may have one last step to take, by default the history is not enabled in the Scheduler, to enable the history, click on search and enter Task Scheduler, right-click and then run as administer. Now in the action pane click Enable all Task History
If you now click refresh, in the scheduler and scroll through the tasks, you will find the job you just created, right-click the job and the run, refresh the scheduler again and then view the history to see if your task completed successfully.
That's the end of this blog about Powershell scheduled task; I hope you found it helpful.