Exporting/Importing all Scheduled Tasks with PowerShell

Tags: PowerShell, Windows, Windows Server

I'm just going to leave this here where I can find it in future.


$SchedRoot = New-Object -ComObject("Schedule.Service")

$OutRoot = "C:\Temp\Tasks"
$OutDirPath = "{0}\{1}"
$OutPath = "{0}\{1}\{2}.XML"

function DoRecurse ($Sched)
  $taskFolder = $Sched.GetFolder($TaskPath)
  foreach ($folder in $taskFolder.GetFolders(0))
    DoRecurse $Sched.GetFolder($folder.Name)
  $tasks = $taskFolder.GetTasks(0)
  $tasks | %{
    $xml = $_.Xml
    $task_name = $_.Name
    $outdir = [string]::Format( $OutDirPath, $OutRoot, $Sched.Path)
    mkdir $outdir -erroraction silentlycontinue  -warningaction silentlycontinue
    $outfile = [string]::Format( $OutPath, $OutRoot, $Sched.Path, $_.Name)
    $xml | Out-File $outfile
DoRecurse $SchedRoot


$SchedRoot = New-Object -ComObject("Schedule.Service")
$TaskModeCreateOrUpdate = 6    # http://msdn.microsoft.com/en-us/library/windows/desktop/aa382577%28v=vs.85%29.aspx
$TaskLogonServiceAccount = 5    # http://msdn.microsoft.com/en-us/library/windows/desktop/aa382577%28v=vs.85%29.aspx

$InRoot = "C:\Temp\Tasks"
$FileSpec = "*.xml"

function DoRecurse ($Path)
  $Dir = Get-Item($Path)
  $TaskPath = "\" + $Dir.FullName.SubString($InRoot.Length+1,$Dir.FullName.Length-$InRoot.Length-1)
  #$TaskParent = $TaskPath.Trim($Dir.Name)

  $taskFolder = $SchedRoot.GetFolder($TaskPath)
  foreach ($Item in $Dir.GetFiles($FileSpec))
    $TaskName = $Item.Name -iReplace(".xml", "")
    $TaskXML = Get-Content $Item.FullName
    $Task = $SchedRoot.NewTask($null)
    $Task.XMLText = $TaskXML

    $taskFolder.RegisterTaskDefinition($TaskName, $Task, $TaskModeCreateOrUpdate, $null, $null, $TaskLogonServiceAccount, $null)

  foreach ($Item in $Dir.GetDirectories())
      DoRecurse $Item.FullName

DoRecurse $InRoot

The powershell scripts here will export and import an entire Task Scheduler database. Perfect for when your client won't get a certificate because the task scheduler database is corrupted. Note that the assumption here is that all tasks are using system-type accounts.

These scripts build on the work at http://jon.netdork.net/2011/03/10/powershell-and-importing-xml-scheduled-tasks/.

No Comments