我正在尝试创建一个警报,该警报将查看目录并通过电子邮件发送所有1kb或更少文件的列表。目前它正在为每个文件发送一封电子邮件。我希望将违规文件放在一封电子邮件中。
$date= Get-Date -Format yyyyMMdd
$path= "c:\test\$date"
$files = Get-ChildItem -Path $path -Recurse
$body = "These files are too small."
$body += "<table><tr><td><b>Filename</b></td></tr>";
foreach ($file in $files) {
if ($file.Length -lt 1kb) {
$body += "<tr><td>" + $($file.Name) + "</td></tr>"
}
};
$body += "</table>"
foreach ($item in [System.IO.Directory]::GetFiles($path)) {
$a=get-item($item)
if ($a.Length -lt 1kb) {
Send-MailMessage -From noreply@email.com -To person@email.com -Subject "Files small" -Body $body -BodyAsHtml -SmtpServer 0.0.0.0
}
}
答案 0 :(得分:1)
你要循环两次。只需移除Send-MailMessage
周围的循环:
$body += "<table><tr><td><b>Filename</b></td></tr>"
foreach ($file in $files) {
if ($file.Length -lt 1kb) {
$body += "<tr><td>" + $($file.Name) + "</td></tr>"
}
}
$body += "</table>"
Send-MailMessage -From noreply@email.com -To person@email.com -Subject "Files small" -Body $body -BodyAsHtml -SmtpServer 0.0.0.0
您可以添加一个标志变量来指示是否找到文件:
$body += "<table><tr><td><b>Filename</b></td></tr>"
foreach ($file in $files) {
if ($file.Length -lt 1kb) {
$fileFound = $true
$body += "<tr><td>" + $($file.Name) + "</td></tr>"
}
}
$body += "</table>"
if ($fileFound) {
Send-MailMessage -From noreply@email.com -To person@email.com -Subject "Files small" -Body $body -BodyAsHtml -SmtpServer 0.0.0.0
}