1
votes

Running the command below creates the task and has the correct settings. The "if the task is not scheduled to run again delete it after 50 seconds is set. The command takes about 10 seconds to run. The problem is that it never actually deletes the task from task scheduler.

$run = (Get-Date).AddMinutes(1) # Two minutes from now
Register-ScheduledTask -TaskName $taskname -InputObject (
  (
    New-ScheduledTask -Action (
      New-ScheduledTaskAction -Execute "powershell.exe" -Argument ( 
"C:\Send-HipchatNotification.ps1 -room '$room' -message '$message' -color 
'purple' -notify"       
      )
    ) -Trigger (
      New-ScheduledTaskTrigger -Once -At ($run.TimeOfDay.ToString("hh\:mm")) 
# As a "TimeOfDay" to get 24Hr format
   ) -Settings (
      New-ScheduledTaskSettingsSet  -DeleteExpiredTaskAfter 00:00:50 # 
Delete one second after trigger expires
    ) 
  ) | %{ $_.Triggers[0].EndBoundary = $run.AddMinutes(60).ToString('s') ; $_ 
} # Run through a pipe to set the end boundary of the trigger
)`
1
You can edit you code by using 4 space before every lines. It will give a better presentation than the use of a simple backtic ` - Nathan Ripert

1 Answers

1
votes

So, I have been testing your script for anomalies and found that there might be a bug in Task Scheduler.

I noticed that once the trigger expires, if you do a

Set-ScheduledTask $taskname

the task is deleted. Otherwise, if the task is left alone, it will leave a ghost object in memory.

Furthermore, if you go into Task Scheduler GUI, and try to edit the task after its expiration, it will give you an error that the Task does not exist and will delete itself from memory indefinitely (and presumably until after reboot, but I haven't tested that far).

I'm not sure if this bug has been reported, but to work around it, you might need to run a Set-ScheduledTask after it has been expired to remove the task object.