
You will find in this post two scripts to :
- create scheduled tasks on remote computers
- get scheduled tasks on remote computers
These actions will be performed using xml and the COM object Schedule.Service. I will write another article on how to manage scheduled tasks with the builtin Powershell cmdlets get-scheduledTask and set-scheduledtask available since Windows 2012 OS.
Create a scheduled task using a xml file on the remote computers server01 and server02:
$servers = "server01","server02"
$task_path = "c:\Temp\mytask.xml"
$task_user = "username"
$task_pass = "password"
$servers | % {
$sch = New-Object -ComObject("Schedule.Service")
$sch.connect($_)
$folder = $sch.GetFolder("\")
Get-Item $task_path | % {
$task_name = $_.Name.Replace('.xml', '')
$task_xml = Get-Content $_.FullName
$task = $sch.NewTask($null)
$task.XmlText = $task_xml
$folder.RegisterTaskDefinition($task_name, $task, 6, $task_user, $task_pass, 1, $null)
}
}
List the user-defined (Principal ID = Author) scheduled tasks and their properties on the remote servers “server01” and “server02” :
$servers = "server01","server02"
$servers | % {
$sch = New-Object -ComObject("Schedule.Service")
$sch.connect($_)
$folder = $sch.GetFolder("\")
$array=@()
$folder.gettasks(0) | % {
$xml = [xml]$_.xml
if ($xml.Task.Principals.Principal.id -eq "Author") {
$array += New-Object psobject -Property @{
"Name" = $_.Name
"Status" = switch($_.State) {0 {"Unknown"} 1 {"Disabled"} 2 {"Queued"} 3 {"Ready"} 4 {"Running"}}
"Command" = $xml.Task.Actions.Exec.Command
"Argument" = $xml.Task.Actions.Exec.Arguments
"NextRunTime" = $_.NextRunTime
"LastRunTime" = $_.LastRunTime
"LastRunResult" = $_.LastTaskResult
"Author" = $xml.Task.Principals.Principal.UserId
"Created" = $xml.Task.RegistrationInfo.Date
}
}
}
$array | fl Name,Status,Command,Argument,Actions,NextRuNTime,LastRunTime,LastRunResult,Author,Created
}
My Powershell script categories
- Active Directory
- Cluster
- Database
- Exchange
- Files and folders
- Hardware
- Network
- Operating System
- PKI
- SCCM
- Service and process
- Tips
- VMWare
Play with the Windows Task Scheduler and XML
