bhanu prakash
bhanu prakash

Reputation: 133

How to Use IF Condition?

My requirement is, the script needs to be sent an email to set of people whenever application pool recycled. Script will search for application pool event IDs from Event Viewer and will send an email if it find any events. If it's found the Event ID it will create an log file in D:\temp and send that log file to recipients.

The problem is, the script is sending an email with empty log file as attachment when no events happen. I dont want to send empty file and script should sent ONLY when event occurs. This can be resolved if we use an if condition, but not sure how to use that in my script.

Below is the script which I used to run. Currently it is sending log when events occur and not occur as well.

$date = Get-Date -Format "MM-dd-yyyy HH-mm-ss"

$starttime = (Get-Date).AddMinutes(-5)

Get-WinEvent -ComputerName computer1 -Filterhashtable @{
    LogName='system';
    StartTime=$StartTime;
    ID=3201,5079,2262,2263,5070,5074,5075,5076,5077,5078,5080,5081,5093,5117,5186
  } |
  select machinename,timecreated,id,message |
  Format-Table machinename,timecreated,id,message -AutoSize |
  Out-String -Width 6096 |
  Out-File "D:\Logs\PS\$date.txt" -NoClobber

Send-MailMessage -To [email protected] `
  -Subject "Application Pool Recycled in Computer1" `
  -Body "Application Pool has Recycled in Computer1" `
  -SmtpServer smtp.com `
  -From [email protected] `
  -Attachments "D:\Logs\PS\$date.txt"

Upvotes: 0

Views: 81

Answers (2)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200483

Check if you actually got an event before creating output and sending mail:

$evt = Get-WinEvent -ComputerName computer1 -Filterhashtable @{...}
if ($evt) {
  $evt | Format-Table ... |
    Out-String -Width 6096 |
    Out-File "D:\Logs\PS\$date.txt" -NoClobber

  Send-MailMessage ...
}

If you want the message inline instead of as an attachment put the event string in a variable and put that in the message body:

if ($evt) {
  $msg = $evt | Format-Table ... | Out-String -Width 6096

  Send-MailMessage ... -Body "Application Pool has Recycled in Computer1`n$msg" ...
}

Upvotes: 2

Kiran Reddy
Kiran Reddy

Reputation: 2904

read the contents of the logfile..if the log file contains data then send email otherwise do nothing.

if(Get-Content -Path "D:\Logs\PS\$date.txt")
{
  #send email.......
}

Upvotes: 1

Related Questions