Como exportar tarefas agendadas com PowerShell

Gostamos de migrar todas as tarefas agendadas para outro servidor ou computador. Em vez de exportar as tarefas agendadas individualmente no Agendador de tarefas, é melhor executar um script do PowerShell para exportar em massa todas as tarefas para você. Também é excelente executar o script e salvar as tarefas agendadas para fins de backup. Neste artigo, você aprenderá como exportar tarefas agendadas com o PowerShell.

Exportar tarefa agendada no Agendador de Tarefas

Não há como exportar várias ou todas as tarefas agendadas do programa Agendador de Tarefas. Só é possível exportar um único agendamento de tarefas.

Selecione todas as tarefas no Agendador de Tarefas e não há opção de exportação.

Selecione uma única tarefa no Agendador de tarefas e você poderá exportar essa tarefa.

Se você tiver muitas tarefas agendadas, isso pode consumir muito tempo. Então, qual é a melhor abordagem? PowerShell para o resgate.

Exporte todas as tarefas agendadas com PowerShell

Para exportar todas as tarefas agendadas, usaremos oTarefa agendadacmdlet do PowerShell para recuperá-los e oTarefa agendada de exportaçãoCmdlet do PowerShell para exportá-los.

Vamos examinar isso na próxima etapa.

Baixe o script Export-SchedTasks do PowerShell

Crie duas pastas no(C:)dirigir:

Veja também:Maneira comprovada de evitar a criação de novas tarefas agendadas no Windows 11

  • Roteiros
  • Tarefas

Baixe e coloque o script Export-SchedTasks.ps1 do PowerShell noC: Scriptspasta. O script exportará todas as tarefas agendadas para oC:Tarefaspasta.

Observação:Ele não exportará a pasta Microsoft que contém tarefas agendadas porque são tarefas padrão.

Certifique-se de que o arquivo esteja desbloqueado para evitar erros ao executar o script. Leia mais no artigo Erro não assinado digitalmente ao executar o script do PowerShell.

Outra opção é copiar e colar o código abaixo no Bloco de Notas. Dê-lhe o nomeExportar-SchedTasks.ps1e coloque-o noC: Scriptspasta.

<#
    .SYNOPSIS
    Export-SchedTasks.ps1

    .DESCRIPTION
    Export Windows Scheduled Tasks on Windows Server and Windows Clients for backup purposes.

    .LINK
    www.alitajran.com/export-scheduled-tasks-powershell/

    .NOTES
    Written by: ALI TAJRAN
    Website:    www.alitajran.com
    LinkedIn:   linkedin.com/in/alitajran

    .CHANGELOG
    V1.00, 12/08/2023 - Initial version
#>

# Define the backup path
$backupPath = "C:Tasks"

# Get the unique task folders from the scheduled tasks
$taskFolders = (Get-ScheduledTask).TaskPath | Where-Object { ($_ -notmatch "Microsoft") } | Select-Object -Unique

# Start exporting of scheduled tasks
Write-Host "Start exporting of scheduled tasks." -ForegroundColor Cyan

# Check if the backup path exists
if (Test-Path -Path $backupPath) {
    Write-Host "Folder already exists: $backupPath" -ForegroundColor Yellow
}
else {
    # Create the backup path if it doesn't exist
    New-Item -ItemType Directory -Path $backupPath | Out-Null
    Write-Host "Backup path created: $backupPath" -ForegroundColor Green
}

# Loop through each task folder
foreach ($taskFolder in $taskFolders) {
    Write-Host "Task folder: $taskFolder" -ForegroundColor Cyan

    # Check if the task folder is not the root folder
    if ($taskFolder -ne "") {
        $folderPath = "$backupPath$taskFolder"

        # Create the task folder in the backup path if it doesn't exist
        if (-not (Test-Path -Path $folderPath)) {
            New-Item -ItemType Directory -Path $folderPath | Out-Null
        }
        else {
            Write-Host "Folder already exists: $folderPath" -ForegroundColor Yellow
        }
    }

    # Get the tasks in the task folder
    $tasks = Get-ScheduledTask -TaskPath $taskFolder -ErrorAction SilentlyContinue

    # Loop through each task in the task folder
    foreach ($task in $tasks) {
        $taskName = $task.TaskName

        # Export the task and save it to a file
        $taskInfo = Export-ScheduledTask -TaskName $taskName -TaskPath $taskFolder
        $taskInfo | Out-File "$backupPath$taskFolder$taskName.xml"
        Write-Host "Saved file $backupPath$taskFolder$taskName.xml" -ForegroundColor Cyan
    }
}

# Exporting of scheduled tasks finished
Write-Host "Exporting of scheduled tasks finished." -ForegroundColor Green

É assim que parece.

Execute o script PowerShell de exportação de tarefas agendadas

Execute o script Export-SchedTasks.ps1 do PowerShell para obter todas as tarefas agendadas e exportá-las para arquivos XML noC:Tarefaspasta.

C:scripts.Export-SchedTasks.ps1

A saída mostra:

Start exporting of scheduled tasks.
Backup path created: C:Tasks
Task folder: 
Saved file C:TasksCreateExplorerShellUnelevatedTask.xml
Saved file C:TasksMicrosoftEdgeUpdateTaskMachineCore{68B94FCC-61AA-45EA-B214-C666C5A7C344}.xml
Saved file C:TasksMicrosoftEdgeUpdateTaskMachineUA{B5BEDAA1-3440-4D7D-A459-0A8C98600F11}.xml
Saved file C:TasksUser_Feed_Synchronization-{D86918D5-2FFC-4B1D-9AF1-0B66C68F64B2}.xml
Saved file C:Taskswin-acme renew (acme-v02.api.letsencrypt.org).xml
Task folder: Mozilla
Saved file C:TasksMozillaFirefox Background Update 308046B0AF4A39CB.xml
Saved file C:TasksMozillaFirefox Default Browser Agent 308046B0AF4A39CB.xml
Exporting of scheduled tasks finished.

Verifique os arquivos XML de tarefas agendadas

O script Export-SchedTasks.ps1 do PowerShell exporta em massa todas as tarefas para arquivos XML. Encontre os arquivos XML no caminhoC:Tarefas.

Abra o arquivo XML com seu aplicativo favorito. Por exemplo, Microsoft Edge, Bloco de Notas ou Bloco de Notas++.

O arquivo XML parece excelente.

Isso ajudou você a fazer backup das tarefas agendadas com o PowerShell em arquivos XML?

Conclusão

Você aprendeu como exportar tarefas agendadas com o PowerShell. Primeiro, execute o script Export-SchedTasks do PowerShell. Em seguida, vá para a pasta de exportação para verificar todas as tarefas agendadas exportadas em arquivos XML. O script funciona para Windows Server e clientes Windows.

Você gostou deste artigo? Você também pode gostar da configuração pós-instalação do Windows Server. Não se esqueça de nos seguir e compartilhar este artigo.

Related Posts