Monday, January 5, 2015

Powershell - search log for content / Select-String

Lately I've been playing with Powershell.  I'm still pretty weak, but practice makes perfect :)

One of my projects was to write a simple script that searches specific database logs for an error and email us to alert us when one is found.

Comments on better ways always welcomed!  I'm learning.
Note: testing done with Powershell v4.0

$emailTo = ""
$emailFrom = ""
$smtpServer = "address"
$smtpSubject = "Error detected in logs"
$smtpBody = ""
$path = "c:\pathtologs"

#smtp function
Function smtpSend {
    Send-MailMessage -From $emailFrom -To $emailTo -Subject $smtpSubject -Body $smtpBody -SmtpServer $smtpServer

#search log files and match string.  Convert array from object to string.
$smtpBody = Select-String -Path $path"\*.log", $path"\*.txt" -SimpleMatch "E. 20" -CaseSensitive |Out-String

#call smtpSend function if match found in logs
if ($smtpBody -ne "") {smtpSend}

No comments:

Post a Comment