user2448523
user2448523

Reputation: 21

PowerShell Update Existing Scheduled Task Trigger Start Date and Time

I am attempting to write a script that will update the trigger time for an existing task. For example change the start time from 12am to 3am. It will also need the ability to disable/enable the task which i'm currently able to do. This is what I currently have.

$servers = gc .\servers.txt

$servers | ForEach-Object {
    $srv = $_
    $schedule = New-Object -Com ("Schedule.Service")
    $schedule.Connect("$srv")
    $tasks = $schedule.GetFolder("\").GetTasks(0)
    $totaltasks = $tasks | where {($_.Name -match $matching1)} #-or ($_.Name -match $matching2)}
    $totaltasks | ForEach-Object {
        if ($status -eq "Disable") {
            $_.Trigger = $triggertime #Daily At 3am
            #$_.Triggers.StartBoundary = "2011-10-01T04:00:00"
            #$_.Enabled = $false
            Write-Host "Disabled Task "$_.Name" for server $srv" -ForegroundColor Yellow
        }

        if ($status -eq "Enable") {
            $_.Enabled = $true
            $_.Triggers.StartBoundary = "2011-10-01T04:00:00 #<--- Does not work
            Write-Host "Enabled Task "$_.Name" for server $srv" -ForegroundColor Green
        }

Upvotes: 1

Views: 19759

Answers (3)

Patrick Burwell
Patrick Burwell

Reputation: 173

THE BEST WAY is the Re-register the existing task you need...

You import the xml file and use PowerShell 4+ Scheduled Tasks commands, like this:

$serverslist_daily_0400 = gc fullyqualifiedpath\inputlist.txt
Foreach($servers in $serverslist_daily_0400){
if($server -like '#*'){continue}
$Stt = New-ScheduledTaskTrigger -Daily -At 4:00am
invoke-command -ComputerName $server -ScriptBlock{
$taskname = (Get-ScheduledTask -TaskPath "\"|where Taskname -like "*reboot*").TaskName #<--this assumes you have reboot in the name
$Stt = New-ScheduledTaskTrigger -Daily -At 4:00am
Set-ScheduledTask -TaskName "$taskname" -Trigger $Stt -Verbose -EA Continue -User domain\svcaccounttorunwith -Password passwordwithnoleadingspecialcharacters } #-Action $sta }
}

Upvotes: 0

Rado Rafiringa
Rado Rafiringa

Reputation: 21

Use the following date format :

$_.Triggers.StartBoundary = ('{0:yyyy-MM-dd HH:mm:ss'} -f (Get-Date '10/01/2019 12:33AM'))
# Your Datetime string formatting should expand to: 2019-10-01 00:33:00

Upvotes: 0

postanote
postanote

Reputation: 16096

As for the core of your question...

I am attempting to write a script that will update the trigger time for an existing task.

Why not just use the built-in cmdlets for this use case?

Set-Scheduled​Task Module:scheduledtasks Modifies a scheduled task.

Example 1: Modify a trigger in a scheduled task

$Time = New-ScheduledTaskTrigger -At 12:00 -Once
Set-ScheduledTask -TaskName "SoftwareScan" -Trigger $Time
TaskPath                          TaskName 
--------                          -------- 
\                                 SoftwareScan

Upvotes: 4

Related Questions