Showing posts with label Windows Server 2012. Show all posts
Showing posts with label Windows Server 2012. Show all posts

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: