Managing Windows Scheduled Tasks with PowerShell


7 October 2014, by

Previous article in series

I used to think Windows Scheduled Tasks were rubbish. Not something a proper techy would use.

Actually they’re still not perfect, but they’re hugely better than they once were, and a bit of PowerShell magic can make managing them a breeze.

The cutting edge

In typical PowerShell fashion, the latest and greatest functionality is only available in Windows Server 2012 / Windows 8. I haven’t had the pleasure of using this functionality in full myself, but you can take a look at the full reference. Suppose you want to disable all scheduled tasks in a particular folder – it’s easy:

Get-ScheduledTask -TaskPath "\MyTasks\" | Disable-ScheduledTask

You can use similarly straightforward commands to create tasks, schedule them, etc. Deployment made easy.

Only slightly in the dark ages

If you’re stuck back in Windows Server 2008, you can’t do the above. But all is not lost. A cut-down version of the task scheduler cmdlet library is available as part of the PowerShell Pack from the Windows 7 Resource Kit – Microsoft seem to have lost this from their website but I’ve found a copy that’s still available.

This provides a load of handy cmdlets including Get-ScheduledTask – you can see a full list via:

Get-Command -Module TaskScheduler

Sadly there are some omissions, in particular the Disable-ScheduledTask command I mentioned above. As luck would have it this is precisely what I needed to do. In case it helps anyone else, here’s my workaround – in the form of a pair of scripts that disable all tasks in a folder, and then re-enable them (without enabling any that were disabled in the first place).

DisableScheduledTasks.ps1

Import-Module PowerShellPack

"Disabling all scheduled tasks..."

Get-ScheduledTask -Folder MyTasks
  | Where-Object { $_.Status -ne "Disabled" }
  | ForEach-Object {
      Out-File -Append -InputObject $_.Name -FilePath "DisabledTaskList.txt"
    }

If (!(Test-Path "DisabledTaskList.txt")) {
  "No tasks to disable"
  Return
}

Get-Content DisabledTaskList.txt
  | ForEach-Object { schtasks /Change /TN ( "MyTasks\" + $_ ) /DISABLE }
  | Out-Null

while (Get-ScheduledTask -Folder MyTasks
  | Where-Object { $_.Status -ne "Disabled" }) {
      "Waiting for all scheduled tasks to complete..."
      Start-Sleep -Seconds 5
    }

EnableScheduledTasks.ps1

Import-Module PowerShellPack

If (!(Test-Path "DisabledTaskList.txt")) {
  "No tasks disabled - please run DisableAllScheduledTasks first"
  Return
}

"Enabling all scheduled tasks..."

Get-Content DisabledTaskList.txt
  | ForEach-Object { schtasks /Change /TN ( "MyTasks\" + $_ ) /ENABLE }
  | Out-Null

Remove-Item DisabledTaskList.txt

Hopefully this will help you get your task scheduling automated even if you’re not able to use the latest version of Windows!

Tags:

Categories: Technical

«
»

Leave a Reply

* Mandatory fields


+ eight = 11

Submit Comment