TL;DR
- PowerShellでコマンドラインアプリケーションを実行しその結果をメールで送付する方法について記載する。
環境
- Microsoft Windows Server 2016 Standard (10.0.14393 N/A ビルド 14393)
- PowerShell (PSVersion 5.1.14393.3471)
内容
ソース
以下はtasklist
を使用し、メモリ使用量をメールで送付している例。
メモリリークが発生しサーバーが停止する場合などに原因を調査する際などに使用する。
runcommandandsend.ps1
function ExecCmd([string]$strCmd)
{
$p = [System.Diagnostics.Process];
$pi = [System.Diagnostics.ProcessStartInfo];
$output = [string];
$pi = New-Object System.Diagnostics.ProcessStartInfo;
$pi.FileName = [System.Environment]::GetEnvironmentVariable("ComSpec");
$pi.Arguments = "/c " + $strCmd;
$pi.UseShellExecute = $false;
$pi.RedirectStandardOutput = $true;
#コマンドを実行し標準出力の内容を取得する
$p = [System.Diagnostics.Process]::Start($pi);
$output = $p.StandardOutput.ReadToEnd();
$p.WaitForExit();
return $output;
}
$output = [string[]];
$output = ExecCmd("tasklist");
Send-MailMessage -To "example@example.com" -From "example@example.com" -Subject "実行結果" -Body $output -SmtpServer example.com -Encoding ([System.Text.Encoding]::UTF8)
参考:http://blog.livedoor.jp/hentaiga/archives/51615192.html
タスクスケジューラーでの登録例
「プログラム」にpowershell
、「引数の追加」にps1ファイルのフルパスを指定する。
実行前にPowerShellのスクリプト実行許可を与えておくこと
参考
http://blog.livedoor.jp/hentaiga/archives/51615192.html
https://qiita.com/arachan@github/items/e93c2fec8fe5f7f66bfa
https://qiita.com/nfujita55a/items/73a1fc870ccacbb85df2
https://qiita.com/Targityen/items/3d2e0b5b0b7b04963750