Reputation: 21
Is there a way I can schedule a task using PowerShell that for 30 days runs on daily basis every 15 mins, and after those 30 days it expires?
I have done the scheduling but I am unable to find anything where we can set an expiry date using New-ScheduledTaskSettingsSet
.
Code:
$trigger = New-ScheduledTaskTrigger -Daily -At 9am
$principal = New-ScheduledTaskPrincipal -UserId $user -RunLevel Highest -LogonType ServiceAccount
$task = Register-ScheduledTask -TaskName 'KView' -Description 'Kview setup for monitoring' -Action $action -Trigger $trigger -Principal $principal
#$task.Triggers.StartBoundary = $date
#$task.Triggers.EndBoundary = $date.AddDays(30)
$task.Triggers.Repetition.Duration = 'P1D'
$task.Triggers.Repetition.Interval = 'PT15M'
$task | Set-ScheduledTask -User $user -Password $password
Upvotes: 2
Views: 2268
Reputation: 990
It is also possible to use the same approach specified by @Otter in https://stackoverflow.com/a/68535661/3095259 when creating a new scheduled task. In this case, rather than extracting a scheduled task from the system, you create a new task, as in the example below.
$TaskAction = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-File $ScriptPath"
$TaskTrigger = New-ScheduledTaskTrigger -Once -At $Start -RepetitionInterval $Interval
$TaskTrigger.EndBoundary = $EndDateTime
$TaskPrincipal = New-ScheduledTaskPrincipal -Id $User -UserId $User -LogonType Password -RunLevel Limited
$TaskSetting = New-ScheduledTaskSettingsSet -Compatibility Win8
$Task = New-ScheduledTask -Description $Description -Action $TaskAction -Principal $TaskPrincipal -Trigger $TaskTrigger -Settings $TaskSetting
$Task | Register-ScheduledTask -TaskName $Name -TaskPath $TaskPath -User $User -Password $Password | Out-Null
Upvotes: 1
Reputation: 1141
Below is an example of the code that will set the expiry for you, just change the TargetTask
name and EndBoundary
value.
Notice that Triggers are arrays. This scheduled task only has one trigger, so we leave it as $Task.Triggers[0]
.
# Fetch the scheduled task object
$Task = Get-ScheduledTask -TaskName "Test"
# Set the date and time it will expire
$Task.Triggers[0].EndBoundary = [DateTime]::Now.AddDays(1).ToString("yyyy-MM-dd'T'HH:mm:ss")
$Task | Set-ScheduledTask
Upvotes: 2