AB2112
AB2112

Reputation: 71

Powershell Script to search a file and then send an email

I am new to Powershell

I am creating a file with output in it and then search that file for a specific phrase and if it contains it, get sent an email. I've been able to create the file and then filter out what I need using sls but I can't seem to figure out how to get that file sent to me via email if it contains a specific word.

Ex - If the file contains the word Offline send that file attached to an email.

These are the following commands I've run so far -

d:
set-location -Path "program files\veritas\volmgr\bin"
.\vmoprcmd >d:\test.data\mediastatus.txt
cd \
set-location -Path "test.data"
sls offline .\mediastatus.txt

Upvotes: 1

Views: 1770

Answers (1)

Maximilian Burszley
Maximilian Burszley

Reputation: 19694

So in your situation-

  • you have output that's generated by this vmoprcmd executable
  • it's redirected to a file
  • you want to detect whether the file/output contains the string "Offline"
  • if it does, trigger an email

To achieve this, you can utilize the Select-String and Send-MailMessage cmdlets:

$Output = 'D:\test.data\mediastatus.txt'
& 'D:\Program Files\veritas\volmgr\bin\vmoprcmd.exe' > $Output

if (Select-String -Pattern offline -Path $Output -Quiet) {
    $MailArgs = @{
        'To'          = '[email protected]'
        'From'        = '[email protected]'
        'Subject'     = 'Device offline!'
        'Attachments' = $Output
        'Body'        = 'Whatever you want it to be'

        'SmtpServer'  = 'my.smtp.server.com'
        'Port'        = 25
    }
    Send-MailMessage @MailArgs
}

Documentation:

Upvotes: 2

Related Questions