CoffeeCoder
CoffeeCoder

Reputation: 303

Send email if character/string detected in PowerShell

Problem: I need a PowerShell script that checks each file in a folder for a specific character (#), then emails the filename only if the character was found.

What I have: I'm still new to loops/testing logic and not sure where it would fit in. My current script successfully checks for the bad character, but emails regardless if something was found or not.

$scr = dir \\fileshare\businessfolder\filedrop | Select-String '#'

$FromAddress = "[email protected]"

$ToAddress = "[email protected]"

$MessageSubject = "Bad Character Detected"

$SendingServer = "mail.something.com"

$SMTPMessage = New-Object System.Net.Mail.MailMessage $FromAddress, $ToAddress, $MessageSubject,$scr

$SMTPClient = New-Object System.Net.Mail.SMTPClient $SendingServer

$SMTPClient.Send($SMTPMessage)

This currently outputs in an email:

\fileshare\businessfolder\filedrop\AD060101.107:3:#N/A \fileshare\businessfolder\filedrop\AD060102.107:3:#N/A \fileshare\businessfolder\filedrop\AD060101.103:14:#N/A

The files I'm scanning through are formatted in this way:

AHMMDDNN.LLL

ADMMDDNN.LLL

The AH/AD indicates if it's the header or detail, the MMDD is month/day, and NN is if it's the first generated file for the day, second generated file, et cetera. LLL is the location number.

What I really want: To take it a step further, I would like to delete the bad file header & detail file and email the extension to the business unit.

The process would be:

  1. Scan for '#' in all files in the folder.
  2. Delete the ADMMDDNN.LLL and corresponding AHMMDDNN.LLL file. (Example: AD060101.107 had a '#' in it, so delete that and the AH060101.107 file too)
  3. Send an email stating "location LLL has been deleted, please recreate file". (Example: "Location 107 has been deleted, please recreate file")

Upvotes: 2

Views: 670

Answers (1)

Martin Brandl
Martin Brandl

Reputation: 58931

Just iterate over all matches from the Select-String cmdlet and use a regex to create a pattern for the Remove-Item (alias rm) cmdlet like A[D|H]060101.103:

$filesToDelete = Select-String -Path '\\fileshare\businessfolder\filedrop\*' -Pattern '#'

$filesToDelete | ForEach-Object {
        'location {0} has been deleted, please recreate file' -f ($_.Filename -split '\.')[-1]
         $_.Path -replace '(.*\\A).(.*)', '$1[D|H]$2'  | rm -Force -ea 0
    }

Note: I omit the E-Mail part but added the message to the foreach.

Upvotes: 1

Related Questions