Skip to content

PowerShell

David Hall edited this page Jul 19, 2018 · 4 revisions

As a .NET library, all of the Task Scheduler Managed Wrapper can be used from within PowerShell. You simply need to load the assembly and then use the interop methods, like New-Object, to interact with the classes.

Create a task using shorthand method

using namespace Microsoft.Win32.TaskScheduler
[Reflection.Assembly]::LoadFile("C:\CodePath\Microsoft.Win32.TaskScheduler.dll")
[TaskService]::Instance.AddTask("Test", [QuickTriggerType]::Hourly, "cmd", "/param1")

Create a complex task

using namespace Microsoft.Win32.TaskScheduler
[Reflection.Assembly]::LoadFile("C:\CodePath\Microsoft.Win32.TaskScheduler.dll")

# Assign the local instance to a variable
$ts = [TaskService]::Instance

# Create a new task definition for the local machine and assign properties
$td = $ts.NewTask()
$td.RegistrationInfo.Description = "Does something"
$td.Settings.Hidden = $true

# Add a trigger that, starting tomorrow, will fire every other week on Monday
# and Saturday and repeat every 10 minutes for the following 11 hours
$wt = New-Object WeeklyTrigger([DaysOfTheWeek] "Monday, Saturday", 2)
$wt.StartBoundary = [DateTime]::Today.AddDays(1)
$wt.Repetition.Duration = [TimeSpan]::FromHours(11)
$wt.Repetition.Interval = [TimeSpan]::FromMinutes(10)
$td.Triggers.Add($wt)

# Create an action that will launch Notepad whenever the trigger fires
$td.Actions.Add("notepad.exe", "c:\\test.log")

# Register the task in the root folder of the local machine
# Notice the use of the [NullString]::Value to give a truly 'null' value. Otherwise PS converts to "".
$ts.RootFolder.RegisterTaskDefinition("Test", $td, [TaskCreation]::CreateOrUpdate,
   $td.Principal.ToString(), [NullString]::Value, [TaskLogonType]::S4U, [NullString]::Value)

# Delete task to cleanup test - DON'T DO THIS IF YOU WANT TO KEEP THE TASK
$ts.RootFolder.DeleteTask("Test")