Tuesday, March 12, 2013

Tailing Log Files in Powershell

Want to watch a log file on a windows box and have the console window constantly updated as the file grows?  Open up powershell and type:

gc c:\somefile.log -wait

Want to watch a log file and only show lines that contain the word "Error?"

gc c:\somefile.log -wait | ? { $_.Contains("Error") }

Want to watch a log file and have it send you an email any time an error message occurs in the log file?


gc trace.log -wait | ? { $_.Contains("Error") } | % { Send-MailMessage -to "myinbox@wherever.com" -from "mysmtpinbox@wherever.com" -bodyAsHTML ("An error occurred: <br/><br/> + $_ } -smtpserver "smtp.myserver.com" }
Want to do the same with an SMTP server that requires authentication?


$username = "mysmtpinbox@wherever.com"
$password = ConvertTo-SecureString "mysmtppassword" -AsPlainText - Force
$creds = New-Object System.Management.Automation.PSCredential($username, $password)

gc trace.log -wait | ? { $_.Contains("Error") } | % { Send-MailMessage -to "myinbox@wherever.com" -from "mysmtpinbox@wherever.com" -bodyAsHTML ("An error occurred: <br/><br/> + $_ } -smtpserver "smtp.myserver.com" -credential $creds }

No comments: