Private/New-pseScheduledTaskTrigger.ps1
Function New-pseScheduledTaskTrigger { [cmdletbinding()] param ( [string]$trigger, [datetime]$time, [int]$RandomiseTaskUpToXMinutes, [int]$DelayTaskUpToXMinutes, [int]$RepeatEveryXMinutes ) # Task Trigger try { Write-Host "Assigning Trigger settings" -ForegroundColor DarkGray switch ($trigger) { 'AtStartup' { Write-Host "Selected trigger is: AtStartup" -ForegroundColor DarkGray; $taskTrigger = New-ScheduledTaskTrigger -AtStartup -ea Stop -ev x } 'AtLogon' { Write-Host "Selected trigger is: AtLogon" -ForegroundColor DarkGray; $taskTrigger = New-ScheduledTaskTrigger -AtLogOn -ea Stop -ev x } 'Daily' { Write-Host "Selected trigger is: Daily" -ForegroundColor DarkGray $taskTrigger = New-ScheduledTaskTrigger -Daily -At $time -ea Stop -ev x if ($RandomiseTaskUpToXMinutes) { $randomDelay = New-TimeSpan -Minutes $RandomiseTaskUpToXMinutes -ea stop $randomDelayString = 'PT' + $randomDelay.Hours.ToString('00') + 'H' + $randomDelay.Minutes.ToString('00') + 'M' + $randomDelay.Seconds.ToString('00') + 'S' $taskTrigger.RandomDelay = $randomDelayString Write-Host "A new time span: $($randomDelayString) has been set. ($randomiseTaskUpToXMinutes minutes)" -ForegroundColor DarkGray } } } # Add a task delay if selected if ($DelayTaskUpToXMinutes) { $taskDelay = New-TimeSpan -Minutes $DelayTaskUpToXMinutes $delayTime = "PT" + $taskDelay.ToString('hh') + "H" + $taskDelay.ToString('mm') + "M" + $taskDelay.ToString('ss') + "S" $tasktrigger.delay = $delaytime Write-Host "A new time span: $($delayTime) has been set. ($DelayTaskUpToXMinutes minutes)" -ForegroundColor DarkGray } # Repeat the task every x minutes indefinitely if ($RepeatEveryXMinutes) { # Modified Repetition Handling $repetitionPattern = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes $RepeatEveryXMinutes) # # RepetitionDuration is not needed for indefinite repetition $tasktrigger.Repetition = $repetitionPattern.Repetition } Write-Host "Trigger settings assigned successfully" -ForegroundColor DarkGreen return $taskTrigger } catch { Write-Error "An error occured assigning the Trigger settings: $x" -stop } } |