locked
Send-MailMessage if pattern exists RRS feed

  • Question

  • Hi Team,

    I'm trying to fix a script (as below) to only send an email if a pattern exists in a log file.

    Currently the script is:

    $date = Get-Date -UFormat "%Y-%m-%d"
    $2date = (Get-Date $date).AddDays(-1).ToString("yyyy-MM-dd")
    
    $results = Select-String -Path "\\filepathhere\filenamehere $2date.log" -Pattern "sql" -Context 5,0
     
    $From = "from@address.com"
    $To = "to@address.com"
    $Subject = "$2date Log Errors"
    $Body = "log errors for $2date
     
    $results
     
    Browse here to see the error file \\filepathhere\filenamehere $2date.log"
    $SMTPServer = "serveraddresshere"
    $SMTPPort = "25"
    Send-MailMessage -From $From -to $To -Subject $Subject -Body $Body -SmtpServer $SMTPServer -port $SMTPPort

    What I want to do, is only have an email sent IF the pattern is detected in the log file. I can see how to split the "Send-MailMessage" to it's only but I am not sure how to trigger the email if the pattern exists.

    Any help would be appreciated. Thanks.

    Tuesday, July 14, 2020 12:28 AM

Answers

  • Put the code into the "true" part of a conditional, like this:

    if ($results){
        <send-the-message>
    }


    --- Rich Matheisen MCSE&I, Exchange Ex-MVP (16 years)

    • Marked as answer by Hi, I'm Poida Tuesday, July 14, 2020 2:20 AM
    Tuesday, July 14, 2020 2:02 AM

All replies

  • Put the code into the "true" part of a conditional, like this:

    if ($results){
        <send-the-message>
    }


    --- Rich Matheisen MCSE&I, Exchange Ex-MVP (16 years)

    • Marked as answer by Hi, I'm Poida Tuesday, July 14, 2020 2:20 AM
    Tuesday, July 14, 2020 2:02 AM
  • Niiice one Gary (Rich). Top work, so simple! Thank you :)
    Tuesday, July 14, 2020 2:20 AM