PowerShell脚本优化:多路径检查后仅发送一次邮件需求
问题需求
现有PowerShell脚本用于检查多个文件夹是否存在新文件,若存在则发送包含日志的邮件。当前脚本在检测到某路径有新文件时会立即发送邮件,而非完成所有路径检查后统一发送一次。需修改脚本实现:完成所有路径检查后,若存在新文件则仅发送一次邮件。
原脚本代码
$source = Get-Content "C:\AAA\source.txt" $logDate = get-date -format yyyy-MM-dd $logtime = get-date -format HH:mm $log = "C:\AAA\$logdate.log" $mailkomu = "EEE@EEE.com" $mailod = "GGG@GGG.com" $subject = "New files in DDD" $zprava = "Message" ForEach($path in $source){ Test-path $path Write-Output "$logtime - $path - ok" | Out-File $log -Append If ((Get-ChildItem -Path $path -Force | Measure-Object).Count -eq 0) { Write-Output "no files" | Out-File $log -Append } Else { Write-Output "new files" | Out-File $log -Append $data = Get-ChildItem -Path $path -Recurse | Select-Object DirectoryName, Name $data | Out-File $log -Append Send-MailMessage -From $mailod -To $mailkomu -Subject $subject -Body $zprava -SmtpServer $SMTPServer -Attachments $log } }
原脚本问题场景
first path - no file - sends no email
second path - new file - sends email with log only for the first and the second path
third path - new file - sends email with log only for the first, second and the third path
fourth path - no file - sends no email
修改后的脚本
$source = Get-Content "C:\AAA\source.txt" $logDate = Get-Date -Format yyyy-MM-dd $logTime = Get-Date -Format HH:mm $log = "C:\AAA\$logDate.log" $mailTo = "EEE@EEE.com" $mailFrom = "GGG@GGG.com" $subject = "New files in DDD" $body = "Message" # 全局标记:是否检测到新文件 $hasNewFiles = $false # 遍历所有路径完成检查与日志记录 foreach ($path in $source) { if (Test-Path $path) { Write-Output "$logTime - $path - 路径正常" | Out-File $log -Append $fileCount = (Get-ChildItem -Path $path -Force | Measure-Object).Count if ($fileCount -eq 0) { Write-Output " → 无文件" | Out-File $log -Append } else { Write-Output " → 检测到 $fileCount 个新文件" | Out-File $log -Append $fileList = Get-ChildItem -Path $path -Recurse | Select-Object DirectoryName, Name $fileList | Out-File $log -Append # 标记存在新文件 $hasNewFiles = $true } } else { Write-Output "$logTime - $path - 路径不存在" | Out-File $log -Append } } # 所有检查完成后,仅当存在新文件时发送一次邮件 if ($hasNewFiles) { Send-MailMessage -From $mailFrom -To $mailTo -Subject $subject -Body $body -SmtpServer $SMTPServer -Attachments $log }
修改要点
- 新增
$hasNewFiles布尔变量,用于统一记录是否在任意路径检测到新文件 - 将邮件发送逻辑移出循环,放到所有路径检查完成后的判断分支中,确保仅发送一次邮件
- 优化日志内容的可读性,补充路径不存在的异常情况处理
- 修正原脚本中
Test-Path未判断返回值的问题,避免错误日志输出
内容的提问来源于stack exchange,提问作者Tomas
相关产品推荐
相关产品推荐

