PowerShell(Task Scheduler)
任意のプログラムを包む PowerShell ラッパーです。プログラムの終了コードで結果を報告します。プログラムの出力は一時ファイルに保存され、失敗したときはその最後の 20 行がアラートに添えられます。
コード
これは Code(コード)タブが生成するコードです(開始とエラー にチェックを入れた状態)。アプリでは、あなたのジョブ専用のアドレスがすでに入っています。
# Save as C:\jobs\taskbeacon-run.ps1
# Task Scheduler > Action: Start a program
# Program: powershell.exe
# Arguments: -NoProfile -ExecutionPolicy Bypass -File C:\jobs\taskbeacon-run.ps1 "C:\path\to\program.exe" "arg1" "arg2"
# Runs the program, then reports success or failure from its exit code.
# A .ps1 script as the program is run with powershell.exe -NoProfile -ExecutionPolicy Bypass -File script.ps1
# (an execution policy set by Group Policy still wins over Bypass).
$tb = "https://taskbeacon.io/ping/your-job-id"
$program, $programArgs = $args
# a .ps1 file is not a program Windows can start on its own ("not a valid Win32 application")
if ($program -match '\.ps1$') {
$programArgs = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $program) + @($programArgs | Where-Object { $null -ne $_ })
$program = 'powershell.exe'
}
function Send-TaskBeacon($path, $text) {
$send = @{ UseBasicParsing = $true; TimeoutSec = 10; Uri = ($tb + $path) }
if ($text) { $send.Method = 'Post'; $send.ContentType = 'text/plain; charset=utf-8'; $send.Body = [Text.Encoding]::UTF8.GetBytes($text) }
try { Invoke-WebRequest @send | Out-Null }
catch { Write-Host "TaskBeacon ping failed: $_" }
}
Send-TaskBeacon "/start"
# keep arguments that contain spaces together
$argLine = ($programArgs | ForEach-Object { if ($_ -eq '' -or $_ -match '[\s"]') { '"' + ($_ -replace '"', '\"') + '"' } else { $_ } }) -join ' '
# Windows PowerShell 5.1 refuses an empty -ArgumentList: pass it only when there are arguments
$run = @{ FilePath = $program; Wait = $true; PassThru = $true; NoNewWindow = $true; ErrorAction = 'Stop' }
if ($argLine) { $run.ArgumentList = $argLine }
# the program's output goes to temporary files: shown below, and its last 20 lines go with a failure
$out = [IO.Path]::GetTempFileName(); $err = [IO.Path]::GetTempFileName()
$run.RedirectStandardOutput = $out; $run.RedirectStandardError = $err
$code = 1
$note = ''
try {
$p = Start-Process @run
if ($null -ne $p.ExitCode) { $code = $p.ExitCode }
} catch { $note = "Could not start ${program}: $_"; Write-Host $note }
Get-Content -LiteralPath $out, $err -ErrorAction SilentlyContinue
$tail = ''
if ($code -ne 0) {
$lines = @(Get-Content -LiteralPath $out, $err -Tail 20 -ErrorAction SilentlyContinue) + @($note)
$tail = ($lines | Where-Object { $_ } | ForEach-Object { if ($_.Length -gt 300) { $_.Substring(0, 300) } else { $_ } }) -join "`n"
}
# the exit code goes at the end of the address: /0 = OK, any other number = failed
Send-TaskBeacon "/$code" $tail
Remove-Item -LiteralPath $out, $err -ErrorAction SilentlyContinue
exit $code # not 0 when it failed, so Task Scheduler shows the failure too仕組み
ラッパーはプログラムの開始時に /start を ping し、終了時には末尾に終了コードを付けたアドレスを ping します:/0 は OK、それ以外の数字は失敗で、出力の最後の 20 行と一緒に送られます。行数は送りません。
一部を省きたい場合は、Code タブでオプションのチェックを外してください。出力を送らず、エラーか終了コードだけを送るには Send output lines(出力行を送信)のチェックを外します。報告できる内容もご覧ください。
コマンドラインからタスクを作成する
上のスクリプトを C:\jobs\taskbeacon-run.ps1 として保存し、それを使ってプログラムを実行するタスクを作成します(コマンド プロンプトで 1 行)。
schtasks /Create /TN "Nightly export" /SC DAILY /ST 02:00 /TR "powershell.exe -NoProfile -ExecutionPolicy Bypass -File C:\jobs\taskbeacon-run.ps1 C:\jobs\export.exe"
ラッパーはプログラムを起動して終わるのを待ち、終了コードをアドレスに入れて結果を報告します(/0 は OK、/1 やその他の数値は失敗)。失敗したときは出力の最後の 20 行も付けます。ラッパーは同じ終了コードで終わるので、Task Scheduler の Last Run Result(前回の実行結果)は TaskBeacon と一致します。
PowerShell スクリプトをジョブにする場合。 ラッパーにプログラムとして .ps1 ファイルを渡します。ラッパー自身が powershell.exe -NoProfile -ExecutionPolicy Bypass -File script.ps1 で実行します(Windows は .ps1 を単独では起動できません:%1 is not a valid Win32 application)。
schtasks /Create /TN "Nightly cleanup" /SC DAILY /ST 03:00 /TR "powershell.exe -NoProfile -ExecutionPolicy Bypass -File C:\jobs\taskbeacon-run.ps1 C:\jobs\cleanup.ps1"
既存のタスクをラップするには、Task Scheduler でそのタスクを開き → Actions → Edit を選びます。Program は powershell.exe、Arguments はスクリプト先頭のコメントのとおりにし、最後にプログラムのパスと引数を付けます。
終了コードが嘘をつく理由
Task Scheduler が知っているのは、自分が起動したプログラムの終了コードだけです。次の 3 つにだまされます。
- 終了コードを隠すラッパー。
.batファイルは最後のコマンドのコードで終わるので、失敗したプログラムの後に成功したcopyがあると0x0になります。 - 常に 0 を返すプログラム。 バッチモードの Stata や多くの社内ツールは、エラーの後でも 0 で終了します。TaskBeacon にあるその言語用のコード(Stata、R、Python …)を使えば、中からエラーを報告できます。
- そもそも実行されない。 PC の電源が切れている、スリープしている、タスクのパスワードの期限が切れている場合、終了コードも通知もありません。TaskBeacon はジョブを Missed(未実行)と表示します。
よくある Last Run Result の値:0x0 成功、0x1 プログラムが 1 を返した(多くは一般的なエラー)、0x41301 タスクが実行中、0x41303 まだ実行されていない。
数値を報告する
ラッパーに見えるのは終了コードだけです。行数を送るには、プログラム自身の言語用のコードを使うか、プログラムから ?rows= 付きで ping を送ってください。
よくある問題
- 手動では動くが、スケジュールでは動かない。 Run whether user is logged on or not(ユーザーがログオンしているかどうかにかかわらず実行する)にチェックを入れ、割り当てたドライブ文字ではなく UNC パスを使ってください。
- "running scripts is disabled on this system"。 引数に
-ExecutionPolicy Bypassを残してください。これはこの実行にだけ適用されます。グループ ポリシーで設定された実行ポリシーはこれより優先されます。Get-ExecutionPolicy -Listで確認し、MachinePolicy か UserPolicy が設定されていれば IT 部門に相談してください。 - "%1 is not a valid Win32 application"。
.ps1がプログラムとして起動されました。ラッパーを使う(.ps1 を扱えます)か、powershell.exe -NoProfile -ExecutionPolicy Bypass -File script.ps1として起動してください。 - スペースを含むパス。 タスクの引数では引用符で囲みます:
"C:\Program Files\Tool\tool.exe"。
ユースケース: Task Scheduler の Last Run Result は 0x0 なのに、スクリプトは失敗した · Task Scheduler はもうメールを送れません:タスクが失敗したときにアラートを受け取る · PowerShell スクリプトのエラーと Task Scheduler の終了コード。その他のご質問: FAQ