vignette/scripts/install-health-sampler-task.ps1

85 lines
2.6 KiB
PowerShell

param(
[string]$Workspace = "D:\workspace\vignette",
[string]$TaskName = "VignetteAdminHealthSampler",
[int]$IntervalMinutes = 5,
[string]$Python = "$env:LOCALAPPDATA\Programs\Python\Python311\python.exe",
[switch]$RunNow,
[switch]$PrintOnly
)
$ErrorActionPreference = "Stop"
if ($IntervalMinutes -lt 1) {
throw "IntervalMinutes must be 1 or greater"
}
$sampleScript = Join-Path $Workspace "scripts\record-admin-health-sample.py"
if (!(Test-Path $sampleScript)) {
throw "Health sampler script not found at $sampleScript"
}
if (!(Test-Path $Python)) {
$pythonCommand = Get-Command python.exe -ErrorAction Stop
$Python = $pythonCommand.Source
}
$userId = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$actionArguments = @(
"-B",
"`"$sampleScript`"",
"--json"
)
if ($PrintOnly) {
Write-Output "Task: $TaskName"
Write-Output "User: $userId"
Write-Output "Action: $Python $($actionArguments -join ' ')"
Write-Output "WorkingDirectory: $Workspace"
Write-Output "Interval: every $IntervalMinutes minute(s), plus at user logon"
return
}
$action = New-ScheduledTaskAction `
-Execute $Python `
-Argument ($actionArguments -join " ") `
-WorkingDirectory $Workspace
$logonTrigger = New-ScheduledTaskTrigger -AtLogOn -User $userId
$repeatTrigger = New-ScheduledTaskTrigger `
-Once `
-At (Get-Date).AddMinutes(1) `
-RepetitionInterval (New-TimeSpan -Minutes $IntervalMinutes)
$settings = New-ScheduledTaskSettingsSet `
-AllowStartIfOnBatteries `
-DontStopIfGoingOnBatteries `
-ExecutionTimeLimit (New-TimeSpan -Minutes 3) `
-MultipleInstances IgnoreNew `
-RestartCount 2 `
-RestartInterval (New-TimeSpan -Minutes 1) `
-StartWhenAvailable `
-WakeToRun
$principal = New-ScheduledTaskPrincipal `
-UserId $userId `
-LogonType Interactive `
-RunLevel Limited
$description = "Records Vignette admin health samples into app.admin_health_event as a one-shot synthetic monitor. Secrets stay in apps/api/.env or the user environment; the task command stores no secrets."
$task = New-ScheduledTask `
-Action $action `
-Trigger @($logonTrigger, $repeatTrigger) `
-Settings $settings `
-Principal $principal `
-Description $description
Register-ScheduledTask -TaskName $TaskName -InputObject $task -Force | Out-Null
Write-Output "Installed scheduled task '$TaskName' for $userId"
Write-Output "Action: $Python $($actionArguments -join ' ')"
Write-Output "Interval: every $IntervalMinutes minute(s), plus at user logon"
if ($RunNow) {
Start-ScheduledTask -TaskName $TaskName
Write-Output "Started scheduled task '$TaskName'"
}