Home > database >  Send email using powershell only if the file is not empty or greater than a particular size
Send email using powershell only if the file is not empty or greater than a particular size

Time:03-03

I have this PS script that sends an email with an attachment that i will be running in a SQL server job.

Send-MailMessage 
-From 'User01 <[email protected]>' 
-To 'User02 <[email protected]>', 'User03 <[email protected]>' 
-Subject 'Sending the Attachment' 
-Body "Forgot to send the attachment. Sending now." 
-Attachments c:\temp\ibn\IBN_1_56_4960135.txt 
-Priority High  
-SmtpServer 'smtp.fabrikam.com' 

This file when empty will be 768bytes so i am trying to add a powershell script to it that checks and does not send an email if this file is this size or less, hence, file is empty.

Any suggestions please?

I found this online but being a Powershell novice it does not say where in the script i need to put it or how to as it did not say in the article.

get-item c:\temp\ibn\IBN_1_56_4960135.txt | foreach -process {if ( $_.length -gt 0 ) { send mail here }} 

Thank you!

CodePudding user response:

Just use what you found to wrap around the Send-Mail.

Get-ChildItem -File -Path 'C:\path\to\myfile.txt' |
    ForEach-Object {
        if ($_.Length -gt 768) {
            Send-MailMessage 
            -From 'User01 <[email protected]>' 
            -To 'User02 <[email protected]>', 'User03 <[email protected]>' 
            -Subject 'Sending the Attachment' 
            -Body "Forgot to send the attachment. Sending now." 
            -Attachments $_.FullName
            -Priority High  
            -SmtpServer 'smtp.fabrikam.com'
        }
    }
  • Related