如何通过邮件发送预定脚本的状态?

时间:2016-02-23 13:35:55

标签: powershell powershell-v2.0 powershell-v3.0

我创建了一个简单的PowerShell脚本,用于使用log_present日期将日志文件从源移动到目标。可以通过邮件通知捕获此报告吗?

Move-Item C:\Users\hxsabe\Desktop\Test\Success_Login.txt H:\Downloads\test

Rename-Item H:\Downloads\test\Success_Login.txt "Success_Login_$(Get-Date -Format "ddMMyyyy").txt"

完成此脚本后,必须在Windows计划任务中安排此脚本。成功/失败任务需要电子邮件通知。

2 个答案:

答案 0 :(得分:0)

$Date = Get-Date -Format "ddMMyyyy"
$Source = "C:\Users\hxsabe\Desktop\Test"
$Destination = "H:\Downloads\test"

move-item $Source\Success_Login.txt $Destination
Rename-Item $Destination\Success_Login.txt "Success_Login_$($Date).txt"

if(Test-Path $Destination\"Success_Login_$($Date).txt")
{
    Send-Mailmessage -smtp x.x.com -from x@x.com -to y@x.com -subject "My Subject"`
                     -Body "Logging successfull"
}
else 
{
    Send-Mailmessage -smtp x.x.com -from x@x.com -to y@x.com -subject "My Subject"`
                     -Body "Logging NOT successfull"
}

您可以测试文件是否与Test-Path一起存在,然后如果成功或不成功,它将发送电子邮件。

答案 1 :(得分:0)

设置$ErrorActionPreference = 'Stop'以强制终止错误,在try..catch块中运行语句,并在Send-MailMessage子句中放置finally语句。

$ErrorActionPreference = 'Stop'
try {
  $src = 'C:\Users\hxsabe\Desktop\Test\Success_Login.txt'
  $dst = "H:\Downloads\test\Success_Login_$(Get-Date -Format 'ddMMyyyy').txt"
  Move-Item $src $dst

  $msg = 'Move successful.'
} catch {
  $msg = 'Move failed.'
} finally {
  Send-MailMessage -Subject $msg -Body $msg ...
}

或者检查automatic variable $?以查看上一次操作是否成功:

$src = 'C:\Users\hxsabe\Desktop\Test\Success_Login.txt'
$dst = "H:\Downloads\test\Success_Login_$(Get-Date -Format 'ddMMyyyy').txt"

Move-Item $src $dst

$msg = if ($?) { 'Move successful.' } else { 'Move failed.' }

Send-MailMessage -Subject $msg -Body $msg ...