2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

コマンドラインアプリケーションを実行して結果をメールで送付する

Posted at

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のスクリプト実行許可を与えておくこと

image.png

参考

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

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?