Friday, November 29, 2013

Create a Scheduled Task With PowerShell

Going into the GUI and creating a scheduled task is not rocket science, and now, either is creating a scheduled task via PowerShell. There is now a ScheduledTasks PowerShell module to help with automating this task. Below is a script for creating a Scheduled Task named Sync AD to SQL. The task runs daily at 6:00am and executes a PowerShell .ps1 file name Sync AD to SQL.ps1. This task is run as a specific domain user.
# Name of Task to create
$taskName = "Sync AD to SQL"
# Location of .PS1 file
$fileLocation = "C:\Scripts\SQL\Sync AD to SQL.ps1"
# UserName to run .PS1 file as
$user = "domain\userName"
# Password for above user
$password = "userPassword" 
# Create Task
$argument = "-Noninteractive -Noprofile -Command &'" + $fileLocation + "'"
$action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument $argument  
$trigger = New-ScheduledTaskTrigger -Daily -At 6am  
$settings = New-ScheduledTaskSettingsSet  
$inputObject = New-ScheduledTask -Action $action -Trigger $trigger -Settings $settings 
Register-ScheduledTask -TaskName $taskName -InputObject $inputObject -User $user -Password $password
If you are not Running the Task as a different user, comment out before the -User as seen below:
Register-ScheduledTask -TaskName $taskName -InputObject $inputObject # -User $user -Password $password
There are a bunch of properties that can be tweaked when creating a scheduled task. Below are the links to the appropriate technet articles for each cmdlet used:
New-ScheduledTaskAction
New-ScheduledTaskTrigger
New-ScheduledTaskSettings
New-ScheduledTask
Register-ScheduledTask

Results:







5 comments:

  1. Excellent! Thanks for this - I've been looking at this feature for ages. Followed your instructions and it works a treat!

    ReplyDelete
  2. This is great! Thanks! Which version of PowerShell supports the above solution?

    ReplyDelete
    Replies
    1. It looks like it will run on PowerShell v3, v4, and v5. I have only tested it on v4 though.

      Delete
  3. hi, how to set up new-scheduledtasktrigger -weekly ???
    -weekly -Day Monday -At 7:00AM << that is what i want to create the schedule...Please help me ^____^

    ReplyDelete