July 27, 2009

Scheduled Tasks using Powershell

How would one go about getting scheduled tasks and other related information to tasks on your machine using Powershell. This was the question asked to me recently. I know there has to be a better way, but here is one way of doing it:
function DumpFolders($folder)
{
$folder

$folder.GetFolders(0) | % {
DumpFolders $_
}
}

# MSDN:
# Pass in 1 to return all running tasks, including hidden tasks.
# Pass in 0 to return a collection of running tasks that are not hidden tasks.
$visibilityFlag = 1

$svc = new-object -com Schedule.Service

$svc.Connect()

Write-Host "-------------------------------"
Write-Host " Folders"
Write-Host "-------------------------------"
DumpFolders $svc.getfolder("\")

$folder = $svc.getfolder("\")

Write-Host "-------------------------------"
Write-Host " Tasks"
Write-Host "-------------------------------"
$folder.GetTasks($visibilityFlag) | select name, path, enabled, lastruntime, nextruntime

Write-Host "-------------------------------"
Write-Host " All Tasks"
Write-Host "-------------------------------"

function DumpFolderTasks($folder)
{
$tasks = $folder.GetTasks($visibilityFlag)
$tasks | % {
@("", "Name: $($_.Name)", "Enabled: $($_.Enabled)", "LastRunTime: $($_.LastRunTime)")
}

$folder.GetFolders(0) | % {
DumpFolderTasks $_
}
}

DumpFolderTasks $svc.getfolder("\")


Anyone have a good way of doing this?

No comments:

Post a Comment