Assets/New-OpsJob.ps1
|
<#
.SYNOPSIS Creates or Updates an Ops Job (Scheduled Task). .DESCRIPTION Registers a Windows Scheduled Task that executes the JobRunner. If the task exists, it updates it (Idempotent). .PARAMETER JobName Name of the job. .PARAMETER ScriptPath Path to the script to execute. .PARAMETER ScheduleTime Time to run the job (e.g., "03:00"). .PARAMETER ServiceAccountUser User to run the task as. Defaults to SYSTEM if not provided. .PARAMETER Interval Repetition interval (e.g., "1.00:00:00" for daily). .PARAMETER ScriptArguments Arguments for the script. .PARAMETER EmailRecipients Emails for alerts. .PARAMETER AlertWebhookUrl Webhook URL for alerts. .PARAMETER RequiredSecrets Secrets to inject. #> param ( [Parameter(Mandatory = $true)] [string]$JobName, [Parameter(Mandatory = $true)] [string]$ScriptPath, [Parameter(Mandatory = $true)] [datetime]$ScheduleTime, [string]$ServiceAccountUser, [timespan]$Interval, [string[]]$ScriptArguments = @(), [string[]]$EmailRecipients = @(), [string]$AlertWebhookUrl, [string[]]$RequiredSecrets = @() ) $ActionPath = "powershell.exe" $RunnerPath = "C:\Ops\Bin\JobRunner.ps1" # Construct Arguments for JobRunner $RunnerArgs = "-ExecutionPolicy Bypass -File `"$RunnerPath`" -JobName `"$JobName`" -ScriptPath `"$ScriptPath`"" if ($ScriptArguments) { $RunnerArgs += " -ScriptArguments " + ($ScriptArguments -join ",") } if ($EmailRecipients) { $RunnerArgs += " -EmailRecipients " + ($EmailRecipients -join ",") } if ($AlertWebhookUrl) { $RunnerArgs += " -AlertWebhookUrl `"$AlertWebhookUrl`"" } if ($RequiredSecrets) { $RunnerArgs += " -RequiredSecrets " + ($RequiredSecrets -join ",") } $Action = New-ScheduledTaskAction -Execute $ActionPath -Argument $RunnerArgs $Trigger = New-ScheduledTaskTrigger -Daily -At $ScheduleTime if ($Interval) { $Trigger.RepetitionInterval = $Interval } if ([string]::IsNullOrWhiteSpace($ServiceAccountUser)) { $ServiceAccountUser = "SYSTEM" } $Principal = New-ScheduledTaskPrincipal -UserId $ServiceAccountUser -LogonType ServiceAccount -RunLevel Highest $Settings = New-ScheduledTaskSettingsSet -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable $TaskName = "OpsJob-$JobName" $ExistingTask = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue if ($ExistingTask) { Write-Host "Updating existing OpsJob: $JobName" Set-ScheduledTask -TaskName $TaskName -Action $Action -Trigger $Trigger -Principal $Principal -Settings $Settings } else { Write-Host "Registering new OpsJob: $JobName" Register-ScheduledTask -TaskName $TaskName -Action $Action -Trigger $Trigger -Principal $Principal -Settings $Settings -Force } |