0

How can I enable a task created using PowerShell's Register-ScheduledTask to be deleted If the task is not scheduled to run again? As in New-JobTrigger -Once -At $ScheduledTime

The option is seen in the Task Scheduler GUI > Task Properties > Settings tab > The last checkbox option reads:

If the task is not scheduled to run again, delete it after: <time period>

MS TechNet article Searching for enabling this option using PowerShell does not turn up any relevant results, mostly how to enable tasks and so on.

user4317867
  • 2,397
  • 4
  • 31
  • 57

1 Answers1

2

You should use a New-ScheduledTaskSettingsSet like

New-ScheduledTaskSettingsSet -DeleteExpiredTaskAfter <TimeSpan>

$STSet = New-ScheduledTaskSettingsSet -DeleteExpiredTaskAfter <TimeSpan>

Register-ScheduledTask mytask -Action <actionobject> -Settings $STSet
Rahul
  • 76,197
  • 13
  • 71
  • 125
  • Good suggestion, but be aware that a task with only one trigger, configured to run once, will "expire" as soon as the trigger fires, so make sure the `TimeSpan` argument is *at least* as long as you would expect the task to maximally run – Mathias R. Jessen Jun 19 '16 at 21:56
  • I'm not sure I have that cmdlet, I'm running v5 and `Get-Command *setting*` does not return the New-ScheduledTaskSEttingsSet cmdlet. – user4317867 Jun 19 '16 at 23:06
  • 1
    @user4317867, which OS version you are using? cause the documentation says *Windows Server 2012 R2 and Windows 8.1* – Rahul Jun 19 '16 at 23:09
  • Ah yes, running Server 2008 R2. I can bring my script over to Server 2012 and see what works. -Thanks! – user4317867 Jun 19 '16 at 23:22
  • Just for fun `New-ScheduledTaskSettingsSet -DeleteExpiredTaskAfter 1 | GM` returns `Microsoft.Management.Infrastructure.CimInstance#Root/Microsoft/Windows/TaskScheduler/MSFT_TaskSettings3` which has the property I'm looking for `DeleteExpiredTaskAfter` thus making the new question, can't I touch this using WMI? – user4317867 Jun 20 '16 at 01:32
  • @user4317867, May be but would suggest you to post another thread with this question and don't forget to accept this one though. – Rahul Jun 20 '16 at 17:39
  • The `-settings` parameter is not available for the cmdlet `Register-ScheduledJob` which I found out is similar to Server 2012 and Win 8.1's `Register-ScheduledTask` – user4317867 Jun 25 '16 at 19:18