0

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.

3
  • I don't know much about PowerShell, I basically avoid Windows altogether. But I would assume you could check the actual filesize instead of using Get-content. Then use filesize to determine whether or not to send the file. Commented May 16, 2013 at 16:26
  • Hi Josiah, thanks for the comment. I have tried with actual filesize but the result was the same . Empty file name is sent. If ((Get-ChildItem "Log.txt") | foreach -process ( $_.length/1MB -gt ("0.00") )) { $smtp.Send($msg) echo "email sent" } else { echo "File is blank" } The thing is that if i create a empty file its size is 0KB, but the log file on the server is 1KB even it is empty. Commented May 16, 2013 at 18:23
  • First of all I know you're new, just thought I'd let you know to wrap your code in backticks to format it in blocks. Secondly what I would do is see how big the file is if you just put one character in it. If it changes to 2KB then just consider anything <= 1KB as blank. Commented May 16, 2013 at 18:52

1 Answer 1

1

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 
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the help. I have managed to do it using Send-Mailmessage and get-content t check if file is empty or not.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.