Managing Scheduled Tasks Remotely Using Powershell

The following Powershell functions allow you to manage querying, creating and removing scheduled tasks on one or more computers remotely.
The functions use schtasks.exe, which is included in Windows. Unlike the Win32_ScheduledJob WMI class, the schtasks.exe commandline tool will show manually created tasks, as well as script-created ones. The examples show some, but not all parameters in action. I think the parameter names are descriptive enough to figure it out, really. If not, take a look at schtasks.exe /?. One tip: try piping a list of computer names to foreach-object and into this function.

Enjoy.
Hugo

Function Get-ScheduledTask
	{
	param([string]$ComputerName = "localhost")
	Write-Host "Computer: $ComputerName"
	$Command = "schtasks.exe /query /s $ComputerName"
	Invoke-Expression $Command
	Clear-Variable Command -ErrorAction SilentlyContinue
	Write-Host "`n"
	}
 
# EXAMPLE: Get-ScheduledTask -ComputerName Server01
 
Function Remove-ScheduledTask
	{
	param(
	[string]$ComputerName = "localhost",
	[string]$TaskName = "blank"
	)
	If ((Get-ScheduledTask -ComputerName $ComputerName) -match $TaskName)
		{
		If ((Read-Host "Are you sure you want to remove task $TaskName from $ComputerName(y/n)") -eq "y")
			{
			$Command = "schtasks.exe /delete /s $ComputerName /tn $TaskName /F"
			Invoke-Expression $Command
			Clear-Variable Command -ErrorAction SilentlyContinue
			}
		}
	Else
		{
		Write-Warning "Task $TaskName not found on $ComputerName"
		}
	}
 
# EXAMPLE: Remove-ScheduledTask -ComputerName Server01 -TaskName MyTask
 
Function Create-ScheduledTask
	{
	param(
	[string]$ComputerName = "localhost",
	[string]$RunAsUser = "System",
	[string]$TaskName = "MyTask",
	[string]$TaskRun = '"C:\Program Files\Scripts\Script.vbs"',
	[string]$Schedule = "Monthly",
	[string]$Modifier = "second",
	[string]$Days = "SUN",
	[string]$Months = '"MAR,JUN,SEP,DEC"',
	[string]$StartTime = "13:00",
	[string]$EndTime = "17:00",
	[string]$Interval = "60"	
	)
	Write-Host "Computer: $ComputerName"
	$Command = "schtasks.exe /create /s $ComputerName /ru $RunAsUser /tn $TaskName /tr $TaskRun /sc $Schedule /mo $Modifier /d $Days /m $Months /st $StartTime /et $EndTime /ri $Interval /F"
	Invoke-Expression $Command
	Clear-Variable Command -ErrorAction SilentlyContinue
	Write-Host "`n"
	}
 
# EXAMPLE: Create-ScheduledTask -ComputerName MyServer -TaskName MyTask02 -TaskRun "D:\scripts\script2.vbs"

Leave a Reply

Close Menu