使用Powershell查找模式并发送电子邮件

时间:2016-01-20 17:15:41

标签: powershell select-string

我有一个脚本,可以在xml文件中搜索模式,然后使用结果创建一个文件。然后,当搜索找到匹配项时,它会通过电子邮件发送文件。但是,这部分不起作用。任何帮助(或调整)将是惊人的:

$date= Get-Date -Format yyyyMMdd
$dir= "c:\test\$date"
$path=Get-ChildItem -Path $dir -Recurse
$pattern = "<RESULT>FAILED</RESULT>"
$submitted = select-string -path $path -pattern $pattern | select Path,Filename | Export-Csv -Path "D:\Failed.csv"
if(@($submitted).Count -eq 0) {
##donothing 
}
else
           {
    Send-MailMessage -From "noreply@email.com" -To users@email.com -Subject "Failed Report" -Body "Attached are the failed files for App" -Attachments "D:\Failed.csv" -SmtpServer 0.0.0.0
    Remove-Item "D:\Failed.csv" -recurse
           }

1 个答案:

答案 0 :(得分:1)

我认为问题出在下面的代码行

$submitted = select-string -path $path -pattern $pattern | select Path,Filename | Export-Csv -Path "D:\Failed.csv"

将其更改为两个语句,如

$submitted = (select-string -path $path -pattern $pattern | measure-object).Count

select-string -path $path -pattern $pattern | select Path,Filename | Export-Csv -Path "D:\Failed.csv"

然后检查条件

if($submitted -eq 0) {
##donothing 
}