在計劃任務中執行 PowerShell 指令碼

建立一個立即執行的計劃任務,然後在啟動時執行 C:\myscript.ps1 作為 SYSTEM

$ScheduledTaskPrincipal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount
$ScheduledTaskTrigger1 = New-ScheduledTaskTrigger -AtStartup
$ScheduledTaskTrigger2 = New-ScheduledTaskTrigger -Once -At $(Get-Date) -RepetitionInterval "00:01:00" -RepetitionDuration $([timeSpan] "24855.03:14:07")
$ScheduledTaskActionParams = @{
    Execute = "PowerShell.exe" 
    Argument = '-executionpolicy Bypass -NonInteractive -c C:\myscript.ps1 -verbose >>  C:\output.log 2>&1"'
}
$ScheduledTaskAction = New-ScheduledTaskAction @ScheduledTaskActionParams
Register-ScheduledTask -Principal $ScheduledTaskPrincipal -Trigger @($ScheduledTaskTrigger1,$ScheduledTaskTrigger2) -TaskName "Example Task" -Action $ScheduledTaskAction