param( [Parameter(Mandatory=$true)][string]$ProjectRoot, [switch]$DryRun ) $ErrorActionPreference = 'Stop' $ProjectRoot = (Resolve-Path $ProjectRoot).Path . (Join-Path $ProjectRoot 'scripts/Initialize-SecurityEnv.ps1') $enabled = (Get-EnvValue ([System.IO.File]::ReadAllText((Join-Path $ProjectRoot '.env'))) 'INFRASTRUCTURE_AUTO_UPDATE_ENABLED') -ne 'false' $hash = [System.Security.Cryptography.SHA256]::Create() try { $id = ([System.BitConverter]::ToString($hash.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($ProjectRoot)))).Replace('-', '').Substring(0, 12) } finally { $hash.Dispose() } $name = "EasyAI-Watchtower-$id" if ($DryRun -and -not $enabled) { Write-Host "更新组件定时任务(dry-run):已关闭"; return } if ($DryRun) { Write-Host "Watchtower 和 updater 定时任务(dry-run):$name,每六小时检查一次"; return } if (-not $enabled) { $existing = Get-ScheduledTask -TaskName $name -ErrorAction SilentlyContinue if ($existing) { Unregister-ScheduledTask -TaskName $name -Confirm:$false } return } $executable = (Get-Process -Id $PID).Path $script = Join-Path $ProjectRoot 'scripts/Update-Infrastructure.ps1' $action = New-ScheduledTaskAction -Execute $executable -Argument "-NoProfile -NonInteractive -ExecutionPolicy Bypass -File `"$script`" -ProjectRoot `"$ProjectRoot`"" $triggers = @('00:17', '06:17', '12:17', '18:17') | ForEach-Object { New-ScheduledTaskTrigger -Daily -At $_ } # Docker Desktop belongs to the logged-in user, not the SYSTEM account. $user = [System.Environment]::UserName if ($env:USERDOMAIN) { $user = "$env:USERDOMAIN\$user" } $principal = New-ScheduledTaskPrincipal -UserId $user -LogonType Interactive -RunLevel Highest $settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -MultipleInstances IgnoreNew -ExecutionTimeLimit (New-TimeSpan -Hours 2) Register-ScheduledTask -TaskName $name -Action $action -Trigger $triggers -Principal $principal -Settings $settings -Force | Out-Null Write-Host '已配置 Watchtower 和 updater 定时任务:每六小时检查一次(Docker Desktop 可用时执行)'