Windows – Modify a scheduled task with PowerShell

powershellscheduled-taskswindows

How can I modify the action step in a scheduled task? We have hundreds of scheduled tasks that point to a particular path and run a PowerShell script. How can we find those tasks and then change the path in the action step without deleting and recreating the entire task?

Best Answer

Scheduled tasks are contained in C:\Windows\System32\Tasks\ and contain XML files. While the Petri article is a good solution for Windows 8 and Windows Server 2012, that's not a complete solution. This should allow you to find the tasks with a specific command or argument, and replace those.

$computer = "localhost"

$oldCommand = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
$oldArguments = "-File `"C:\Users\Public\Scripts\oldScript.ps1`""
$newCommand = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
$newArguments = "-File `"C:\Users\Public\Scripts\newScript.ps1`""

$tasks = Get-ChildItem "\\$computer\c$\Windows\System32\Tasks\" | Where-Object {
    $_.PSIsContainer -eq $false `
    -and `
    (([xml](Get-Content -Path $_.FullName)).Task.Actions.Exec.Command -like $oldCommand) `
    -and `
    (([xml](Get-Content -Path $_.FullName)).Task.Actions.Exec.Arguments -like $oldArguments)
    }

$tasks | ForEach-Object {
    $xml = [xml](Get-Content -Path $_.FullName)
    $xml.Task.Actions.Exec.Command = $newCommand
    $xml.Task.Actions.Exec.Arguments = $newArguments
    $xml.Save($_.FullName)
    }
Related Question