Mochael_DLite
Mochael_DLite

Reputation: 187

Powershell script sends email for every file, only need one email

My script is set to check a directory for files older than 2 days and then an email is sent to the group to submit. If there are files in the directory that were submitted within 2 days, they are thanked. However, the foreach is killing me with multiple emails when multiple files are there. Is there a way to only send one email regardless of the number of files?

$path = "C:\testing\Claims"
Foreach($file in (Get-ChildItem $path *.txt -Recurse))
{
    If($file.LastWriteTime -lt (Get-Date).adddays(-2).date)
    {
    Send-MailMessage `
    -From [email protected] `
    -To [email protected]`
    -Subject "File Not Received" `
    -Body "Your claims files for this week not available.  Please submit them ASAP so that processing can begin." `
    -SmtpServer smtp.smtp.com
    }
Else
    {
    Send-MailMessage `
    -From [email protected] `
    -To [email protected]`
    -Subject "File Received" `
    -Body "We have received your file for this week.  Thank you!" `
    -SmtpServer smtp.smtp.com
    }
    }

Upvotes: 0

Views: 461

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200193

Simply check the number of files that were submitted within the last 2 days and send your mails depending on that number:

$path       = "C:\testing\Claims"
$twoDaysAgo = (Get-Date).AddDays(-2).Date

$submitted = Get-ChildItem $path *.txt -Recurse |
             ? { $_.LastWriteTime -ge $twoDaysAgo }

if (@($submitted).Count -eq 0) {
  Send-MailMessage `
    -From [email protected] `
    -To [email protected]`
    -Subject "File Not Received" `
    -Body "Your claims files for this week not available.  Please submit them ASAP so that processing can begin." `
    -SmtpServer smtp.smtp.com
} else {
  Send-MailMessage `
    -From [email protected] `
    -To [email protected]`
    -Subject "File Received" `
    -Body "We have received your file for this week.  Thank you!" `
    -SmtpServer smtp.smtp.com
}

Upvotes: 2

Related Questions