user1097593
user1097593

Reputation: 11

Powershell send mail

I am having the following problem. I have a powershell script to send me emails with log files attached. The only problem is that I need only the log files that are not empty. So i have tried to use this script:

If ((Get-content "Log.txt") -gt 0 ) {
    $smtp.Send($msg)
    echo "email sent"
    } else {
    echo "File is blank"
    }

It seems that -gt 0 is not working for me. No matter what I have tried powershell still sends me the empty logs. So can you please show me where I am wrong? I have tried this as well:

If ((Get-Content $file) -eq $Null) {
    "File is blank"
    } else {
    $smtp.Send($msg)
    echo "email sent"
    }

But it is still not working.

Thank you in advance.

Upvotes: 0

Views: 1862

Answers (1)

alroc
alroc

Reputation: 28144

Get-Content will read the entire contents of the file - only to throw it all away! That's a huge waste of resources.

Instead, get info from the fileystem itself about the file with get-item or get-childitem.

if ((get-item "log.txt").length -gt 0) {
    do stuff
}

It also looks like you're using an antiquated method of sending email. In PowerShell 2.0 and above, use Send-MailMessage - it's much easier to use. In fact, if you have all the logfiles in one directory, you can distill this to a two-liner:

$logs = get-childitem -path PATH_TO_LOGS|where-object{($_.length -gt 0) -and !$_.PSIsContainer}|select-object -expandproperty fullname
Send-Mailmessage -attachments $logs OTHER_PARAMETERS_HERE

Upvotes: 1

Related Questions