I needed to setup a scheduled task that ran some PowerShell script in Windows Server 2008. When searching the web I noticed that a lot of people had struggled with this and so I decided to write this post to explain how I managed it. The scheduled task will ‘run whether the user is logged on or not’. You can schedule a PowerShell script using task scheduler which will run automatically on a given time.
1. The first thing you need to do is make sure that PowerShell is set to execute PowerShell scripts, instead of only allowing interactive commands to be run in the PowerShell environment. Type the following at the PowerShell command prompt:
Set-ExecutionPolicy RemoteSigned
2. I started with a simple PowerShell script file process.ps1 consisting of only one line
Get-process | Out-FileC:\test\ProcessOutput.txt
3. You then need to create a .bat file which will invoke the PowerShell script file. Copy the below line into notepad and save as BatchProcess.bat
powershell.exe C:\Test\process.ps1
4. Now from the start menu go to “Administrator Tools” and open Task Scheduler
a. From The actions menu Click on “Create Task”
b. Under the General Tab, enter task name ProcessTestTask. Ensure that the “Run when user is logged on or not” and “Run with highest privileges” checkboxes are selected.
c. Ensure that the ‘Configure for’ drop down box is selected for the appropriate operating system.
5. Under the “Trigger” tab, click on “New” and assign a schedule to run the task. Choose times 5 minutes for testing purposes.
6. Click “Ok”
7. Under the “Actions” tab click on “New”. Browse to and select the path to the OutputProcesses.bat file, also add the path into the ‘Start in’ text box (it will be your OutputProcesses.bat file folder path).
8. Click “Ok”.
9. Leave the other tab settings as default and click OK to save the task settings.
10. Try to run it manually by right-clicking on the task and selecting run to check if this works.
11. Then try to log off before the task is scheduled to run to confirm that it works when you are logged off.
12. To find out if this has worked correctly you need to check that the file ProcessOutput.txt has been successfully created in your test directory (“C:\test\”). If this file is successfully created, it means your script works fine.