# Register a Windows scheduled task to run run-daily.ps1 # Usage: # .\register-daily-task.ps1 # .\register-daily-task.ps1 -Time "08:50" # .\register-daily-task.ps1 -Unregister param( [string]$Time = "08:50", [string]$TaskName = "DailyRobots", [switch]$Unregister ) $ErrorActionPreference = "Stop" $Root = Split-Path -Parent $MyInvocation.MyCommand.Path $RunScript = Join-Path $Root "run-daily.ps1" $LogDir = Join-Path $Root "logs" $LogFile = Join-Path $LogDir "scheduled-run.log" if ($Unregister) { Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false -ErrorAction SilentlyContinue Write-Host "Removed scheduled task: $TaskName" exit 0 } if (-not (Test-Path $RunScript)) { throw "Not found: $RunScript" } if (-not (Test-Path $LogDir)) { New-Item -ItemType Directory -Path $LogDir | Out-Null } # Append stdout/stderr to logs/scheduled-run.log for troubleshooting $Argument = @( "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", "& { Set-Location '$Root'; & '$RunScript' *>&1 | Tee-Object -FilePath '$LogFile' -Append; exit `$LASTEXITCODE }" ) -join " " $Action = New-ScheduledTaskAction ` -Execute "powershell.exe" ` -Argument $Argument ` -WorkingDirectory $Root $Trigger = New-ScheduledTaskTrigger -Daily -At $Time $Settings = New-ScheduledTaskSettingsSet ` -AllowStartIfOnBatteries ` -DontStopIfGoingOnBatteries ` -StartWhenAvailable ` -ExecutionTimeLimit (New-TimeSpan -Hours 2) $Principal = New-ScheduledTaskPrincipal -UserId $env:USERNAME -LogonType Interactive -RunLevel Limited Register-ScheduledTask ` -TaskName $TaskName ` -Action $Action ` -Trigger $Trigger ` -Settings $Settings ` -Principal $Principal ` -Description "Generate and push daily report (run-daily.ps1)" ` -Force | Out-Null Write-Host "Scheduled task registered:" Write-Host " Name: $TaskName" Write-Host " Time: daily at $Time" Write-Host " Script: $RunScript" Write-Host " Log: $LogFile" Write-Host "" Write-Host "Test now: Start-ScheduledTask -TaskName '$TaskName'" Write-Host "Remove: .\register-daily-task.ps1 -Unregister"