Powershell – How to disable a scheduled task using Powershell

automationpowershellscheduled-taskwindows-server-2008-r2

I have a web application that runs on Windows Server 2008 R2, which has a large number of scheduled tasks which take care of all the backend stuff. When I do a software deployment which touches the database, I need to disable all the scheduled tasks. Currently I have a long checklist that I need to step through manually, disabling each scheduled task as I go – surely this is a job ripe for automation with Powershell.

Unfortunately, the Powershell documentation seems to be fairly coy about how you disable an existing scheduled task (and of course, re-enable it once the release has been completed successfully). I can get a list of ready, running or disabled tasks, but what next?

Best Answer

You can use the COM-based Task Scheduler Scripting objects:

($TaskScheduler = New-Object -ComObject Schedule.Service).Connect("localhost")
$MyTask = $TaskScheduler.GetFolder('\').GetTask("My Task")
$MyTask.Enabled = $false

To enable the task again:

$MyTask.Enabled = $true

The above will only work if the shell is elevated and you are a local Administrator on the server. You could make your own cmdlet with the above:

function Disable-ScheduledTask
{
    param([string]$TaskName,
          [string]$ComputerName = "localhost"
         )

    $TaskScheduler = New-Object -ComObject Schedule.Service
    $TaskScheduler.Connect($ComputerName)
    $TaskRootFolder = $TaskScheduler.GetFolder('\')
    $Task = $TaskRootFolder.GetTask($TaskName)
    if(-not $?)
    {
        Write-Error "Task $TaskName not found on $ComputerName"
        return
    }
    $Task.Enabled = $False
}