Create a scheduled task with PowerShell

Sometimes during OSD I need to create a scheduled task with PowerShell so that the clients runs another script once the user has gotten the client.

In this short post, I will show you how to create a scheduled task that runs a script at logon, all through PowerShell.

To do this, we will use the following cmdlets:

  • New-ScheduledTaskAction
  • New-ScheduledTaskTrigger
  • New-ScheduledTaskPrincipal
  • New-ScheduledTaskSettingsSet
  • New-ScheduledTask
  • Register-ScheduledTask

First we set the action, we will run “powershell.exe” and in the arguments we chose to keep the windows hidden from the user and point to our script.

$action = New-ScheduledTaskAction -Execute "C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe" -Argument "-windowstyle hidden C:\Windows\Temp\script.ps1"

Next, we specify when the script should be run. In our case at logon.

$trigger = New-ScheduledTaskTrigger -AtLogOn

Then we need to specify in what context the script should be run.

$principal = New-ScheduledTaskPrincipal "Administrator" -RunLevel Highest

We can also specify other settings, for example max run time, retries, priority and so on. In this case I will only specify that the script should be run if there is a network connection.

$settings = New-ScheduledTaskSettingsSet -RunOnlyIfNetworkAvailable

Now we have all the basics, so it’s time to create the scheduled task itself by combining all the above.

$task = New-ScheduledTask -Action $action -Principal $principal -Trigger $trigger -Settings $settings

The last step is to give the task a name and to register it on the client, in this case I named it “MyTask”

Register-ScheduledTask MyTask -InputObject $task

That’s all there is to it, nothing that’s hard to do, but if you miss one of the steps above the task will fail to be created without telling you why.

For example, I had to specify $settings, even though I didn’t have any settings that I wanted to specify. (Could have been something temporary though)

For more guides to PowerShell, Click Here

This entry was posted in Powershell and tagged , , , , , . Bookmark the permalink.

One Response to Create a scheduled task with PowerShell

  1. Pingback: PowerShell Guides - A guide to Microsoft ProductsA guide to Microsoft Products

Leave a Reply

Your email address will not be published. Required fields are marked *