Create scheduled task by using Powershell

In the path i wrote about how to schedule a powershell script in Windows. This post is about how to create scheduled task programmatically. Two methods can be used depending on your Windows operating system. If you want to create a scheduled task under windows server 2003 then we should use the schtasks.exe tool. In case of Windows server 2008 or 2008 R2 we can use object model to get our goal.

Script examples

I would like to show you an example how to create a MOSS backup scheduled job.

Windows Server 2003

I create a batch file for backing up the Sharepoint farm then i schedule it to run daily.

$Moss_backupjob_filename = 'd:\MOSS_Backup.bat'
if (Test-Path $Moss_backupjob_filename){Remove-Item $Moss_backupjob_filename}

$text = 'call "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\BIN\stsadm.exe"  -o backup -directory "' + $Global:PathBackup + '" -backupmethod 1 -overwrite'
$text | set-content $Moss_backupjob_filename -Encoding Ascii
$HostName = $env:computername
$username = "Domain\Username"
$password = "Password_cleartext"
$TaskName = 'Moss Farm Backup job'
$TaskRun = '\"' + $Moss_backupjob_filename + '\"'
schtasks /create /s $hostname /ru $username /rp $password /tn $Taskname /tr $TaskRun /sc daily /st 22:00

Windows Server 2008 / 2008 R2

I create a powershell script for backing up the Sharepoint farm then i schedule it to run daily.

$Moss_backupjob_filename = 'D:\MOSS_Backup.ps1'
if (Test-Path $Moss_backupjob_filename){Remove-Item $Moss_backupjob_filename}
#Add the Sharepoint Bin direcotry to the path environment parameter
$text = '$env:path = $env:path + ";C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN"'
$text | out-file $Moss_backupjob_filename -append -encoding Ascii

'$command = "stsadm.exe"' | out-file $Moss_backupjob_filename -append -encoding Ascii

$BackupDir = 'D:\MOSS_Backup\'
if ((Test-Path $BackupDir) -eq $false) { New-Item -type directory -Path $BackupDir}
$text =  '$commandarguments = " -o backup -directory ' + "'" + $BackupDir + "'" + ' -backupmethod 1 -overwrite"'
$text | out-file $Moss_backupjob_filename -append -encoding Ascii

$text = 'start-process -filepath $command -argumentlist $commandargument -wait'
$text | out-file $Moss_backupjob_filename -append -encoding Ascii

'Start-sleep -s 5' | out-file $Moss_backupjob_filename -append -encoding Ascii
$command = 'powershell.exe'
$CommandArguments = ' -c "& '  + " '" + $Moss_backupjob_filename + "'" +' "'
$Hostname = $Env:computername

$taskRunAsuser = "Domain\Username"
$taskRunasUserPwd = "Password_ClearText"

$service = new-object -com("Schedule.Service")
$service.Connect($Hostname)
$rootFolder = $service.GetFolder("\")
$taskDefinition = $service.NewTask(0)
$regInfo = $taskDefinition.RegistrationInfo
$regInfo.Description = 'Moss 2010 Backup - start at 22:00 daily'
$regInfo.Author = $taskRunAsuser
$settings = $taskDefinition.Settings
$settings.Enabled = $True
$settings.StartWhenAvailable = $True
$settings.Hidden = $False
$triggers = $taskDefinition.Triggers
$trigger = $triggers.Create(2)
#$startTime = "2006-05-02T22:00:00"
$trigger.StartBoundary = "2010-06-10T22:00:00"
$trigger.DaysInterval = 1
$trigger.Id = "DailyTriggerId"
$trigger.Enabled = $True
$Action = $taskDefinition.Actions.Create(0)
$Action.Path = $command
$Action.Arguments = $CommandArguments
$rootFolder.RegisterTaskDefinition( 'MOSS 2010 Backup job', $taskDefinition, 6, $taskRunAsuser , $taskRunasUserPwd , 0)
    #If you want the task to be run using a service account without login to the server, just use the next line (take care about the prerequisite in the article below)
    #$rootFolder.RegisterTaskDefinition( 'MOSS 2010 Backup job', $taskDefinition, 6, $taskRunAsuser , $taskRunasUserPwd , 1)

    #For local system account use the next line:
    #$Rootfolder.RegisterTaskDefinition('MOSS 2010 Backup job', $TaskDefinition, 2, "System", $null , 5)

Prerequisite

If you want the task to be run whether the service account user is logged on or not you should disable the “Network acces: do not allow storage of passwords and credentials…” Security policy while the task is beeing created.

Security policy setting for scheduled task creation
SecPol.msc

Conclusion

I think it’s more easy to create such a task using an object model, but if you are looking for the source of that object type (Schedule.Service)… well i haven’t found that till now.

Have fun 🙂

More info

http://msdn.microsoft.com/en-us/library/aa382577(v=vs.85).aspx

Advertisements

4 thoughts on “Create scheduled task by using Powershell”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s