Wednesday, 2 September 2020

powershell 25 backup restore scheduled task

 function backup {
    
    $Alltasks = Get-ScheduledTask

    $backupFolder = "c:\users\bob\desktop\tasks"

    New-Item $backupFolder -ItemType Directory -Force

    $Alltasks | Export-Clixml $backupFolder\backup-info.csv

    foreach ($task in $Alltasks){
        try{
            $result = Export-ScheduledTask -TaskName $task.TaskName -TaskPath $task.TaskPath

            if($result){
                $result | Out-File ("$backupFolder\$($task.TaskName).xml")
            }
            $result = $null
        }
        catch{
            $_
        }
    }
    
}

function restoreTasks(){
    $backupFolder = "c:\users\bob\desktop\tasks"

    $AllItems = Get-ChildItem $backupFolder -Filter *.xml

    foreach ($item in $AllItems){
        [string]$rawxml = Get-Content $item.FullName
        [xml]$xml = $rawxml
        $registration = $xml.Task.RegistrationInfo.URI -split('\\')
        $C = $registration.Count - 1
        $taskname = $registration[$C].Trim()
        $taskpath =  $xml.Task.RegistrationInfo.URI
        try{
            Register-ScheduledTask -Xml $rawxml -TaskName $taskname -TaskPath (Split-Path $taskpath)`
            -ErrorAction SilentlyContinue -Force
        }
        catch{...}
    }
}

function removeTasks {
    Get-ScheduledTask | Unregister-ScheduledTask -Confirm:$false
}  

reference:

No comments:

Post a Comment