Powershell 如何通过邮件发送计划脚本的状态?
我已经创建了一个简单的PowerShell脚本,用于将日志文件从源移动到目标,并带有日志当前日期。是否可以通过邮件通知捕获此报告Powershell 如何通过邮件发送计划脚本的状态?,powershell,powershell-2.0,powershell-3.0,Powershell,Powershell 2.0,Powershell 3.0,我已经创建了一个简单的PowerShell脚本,用于将日志文件从源移动到目标,并带有日志当前日期。是否可以通过邮件通知捕获此报告 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" 完成此脚本后,必须
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计划任务中计划此脚本。成功/失败任务需要电子邮件通知
$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"
}
您可以使用
测试路径测试文件是否存在,然后如果文件成功或未成功,它将发送电子邮件。设置$ErrorActionPreference='Stop'
若要强制终止错误,请在try..catch
块中运行语句,并将sendmailmessage
语句放在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 ...
}
或者检查$?
以查看上一个操作是否成功:
$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 ...
查看send mailmessage或Net.Mail.mailmessage对象。您可以从第二行将文件直接复制到带有日期的文件名。如果我保存为PS1文件并在powershell命令下运行,请帮助我获取错误。下面的帮助是错误。第1行字符:26+C:\Users\hxsabe\Desktop\R&D\success_Move_Report.ps1+~Ampersand不允许。&操作员保留供将来使用;使用“&”将与作为字符串传递CategoryInfo:ParserError:(:)[],ParentContainerRorRecordException+FullyQualifiedErrorId:AmpersandNotAllowedPowerShell不喜欢路径中的ampersand。将路径放在引号中,并使用call操作符运行脚本:&“C:\path\to\your.ps1”