PowerShell Script to retrieve scheduled tasks on a remote machine - Task Scheduler API
Rod Trent posted a PowerShell script for Getting the List of Scheduled Tasks. I have the need the other day to retrieve scheduled tasks on a remote server. I give it a try but to my surprise, it doesn't return anything while I know I have tasks scheduled on that box. Why?
This is because that Windows has two different APIs to manage scheduled tasks
1) The Task Scheduler API used by Task Scheduler and by Schtasks.exe, a command-line task management tool that ships with XP/Windows 2003 and beyond;
2) So called AT APIs used by At.exe and by WMI's Win32_Scheduled class.
So Rod's script covered the AT API and apparently my tasks weren't scheduled that way and hence why I couldn't retrieve anything.
Now the question is can we use script, PowerShell in particular to retrieve the tasks scheduled using Task Scheduler API? Yes, we can! But you will need Windows Vista to accomplish that.
First we need to create an instance of Schedule.Service (COM) object, then we will need to use the connect method to actually connect to the service. By default it will connect to the local machine but you could specify a remote computer to connect to like below, we are connecting to a computer called "Whatever"
$ST = new-object -com("Schedule.Service")
$ST.connect("whatever")
Next we need to retrieve the object reference to the folder we want to search. In my case, that's the root folder(\):
$RootFolder = $ST.getfolder("\")
We then use the GetTasks method to get a collection of all the tasks in the folder targeted.
$ScheduledTasks = $root.GetTasks(0)
The parameter (0) to the GetTasks method is required - Why? I don't know!
Last but not least, We get what what we looking for - The tasks scheduled on the remote machine!
$ScheduledTasks | select name, path, enabled, lastruntime, nextruntime
Name : WhateverUpdater
Path : \WhateverUpdater
Enabled : True
LastRunTime : 7/28/2008 4:30:00 AM
NextRunTime : 7/29/2008 4:30:00 AM
Name : XYZ
Path : \XYZ
Enabled : True
LastRunTime : 7/28/2008 4:00:00 AM
NextRunTime : 7/29/2008 4:00:00 AM
Now with Rod's AT API and my Task Scheduler API, we get Scheduled Tasks covered!