Search code examples
powershellscriptingpowershell-3.0

Sending an email if a File in a folder is older than 1 Minute else do not send anything in Powershell


Here is my code, which sends an email and creates a good subject if a file exists however it sends the email continuously even if there are no files present. I want to use something like "if file.exist then smtp send".

$smtpServer = "test.local"
$smtpTo = "[email protected]";
$messageSubject = "Urgent check....!"
$Message = New-Object System.Net.Mail.MailMessage $smtpFrom, $smtpTo
$Message.Subject = $messageSubject
$content = Get-ChildItem '\\test\test1\test2\*.txt' |
           Where-Object {$_.LastWriteTime -lt (Get-Date).AddMinutes(-1)}
$Message.IsBodyHtml = $true
$style = "<style>BODY{font-family: Arial; font-size: 10pt;}"
$style = $style + "</style>"
$Message.Body = Get-ChildItem '\\test\test1\test2\*.txt' |
                Select-Object -Property "Name", "LastWriteTime" |
                Where-Object {$_.LastWriteTime -lt (Get-Date).AddMinutes(-1)} |
                ConvertTo-Html -Head $style
$smtp = New-Object Net.Mail.SmtpClient ($smtpServer)
$smtp.Send($message)

Solution

  • Check if $content is empty, and only send mail if it's not.

    ...
    $content = Get-ChildItem '\\test\test1\test2\*.txt' |
               Where-Object {$_.LastWriteTime -lt (Get-Date).AddMinutes(-1)}
    
    if ($content) {
        $Message = New-Object Net.Mail.MailMessage $smtpFrom, $smtpTo
        ...
        $Message.Body = $content |
                        Select-Object "Name", "LastWriteTime" |
                        ConvertTo-Html -Head $style
    
        $smtp = New-Object Net.Mail.SmtpClient $smtpServer
        ...
    }
    

    On more recent PowerShell versions you could use the Send-MailMessage cmdlet instead of fumbling around with MailMessage and SmtpClient objects. The general approach would be the same, though.

    ...
    $content = Get-ChildItem '\\test\test1\test2\*.txt' |
               Where-Object {$_.LastWriteTime -lt (Get-Date).AddMinutes(-1)}
    
    if ($content) {
        $body = $content |
                Select-Object "Name", "LastWriteTime" |
                ConvertTo-Html -Head $style
    
        Send-MailMessage -To $smtpTo ... -Body $body -BodyAsHtml -SmtpServer $smtpServer ...
    }