Syncing Scheduled Tasks with Powershell

Posted by & filed under Windows Administration.



The following script will allow you to sync scheduled tasks to a local server from a remote one.  You can modify the source and target folders, and that’s good because this script will wipe out the target folder (the one on the local host) every time it’s run.  Of course you could change that behavior easily.  I keep this scheduled task running in the root of scheduled tasks and it’s never removed.  You could choose to sync the root folder, and use a where clause to make sure you protect certain tasks.

This script also imports the scheduled tasks as disabled.  I’m using this for a failover server, so I want them off.  you can fix that by removing the .replace(“str”,”newstr”) chunk.

Enjoy!


#Run as Admin
#Get Local Scheduler
$localscheduler = New-Object -ComObject("Schedule.Service")
$localscheduler.connect("localhost")
#Set the local tasks folder - this folder will have its tasks all deleted unless you change behavior
$localtaskfolder = $localscheduler.GetFolder("Synced")
$localtasks = $localtaskfolder.GetTasks(0)

#Login Information for new tasks
$tuser = "hostordomain\user"
$tpass = "plaintextpassword" #See other examples that show how to encrypt and decrypt these

#Download scheduled tasks from another scheduler, leave them disabled
$sourcescheduler = New-Object -ComObject("Schedule.Service")
#Here is where you set the remote computer name
$sourcescheduler.Connect("remote")
#Notice that get folder here is pointing to the root of remote
$sourcetasks = $sourcescheduler.GetFolder("\").GetTasks(0)

if ($sourcetasks -ne $null){
$localtasks | %{$localtaskfolder.DeleteTask($_.Name,0)}
$sourcetasks | %{
$tmpTask = $localscheduler.NewTask($null)
#Notice the below line - I'm disabling all these tasks that are imported.  Remove the replace string to change that
$tmpTask.XmlText = ($_.Xml).Replace("<Enabled>true","<Enabled>false")
$localtaskfolder.RegisterTaskDefinition($_.Name, $tmpTask, 6, $tuser, $tpass, 1, $null)
}
}

Leave a Reply

  • (will not be published)