Thursday 7 June 2012

PowerShell: Email me my EventLog, Please.

Today at work I decided to try my hand at PowerShell a little bit.

I DO like it... it's a little tricky to learn any new language, but it is really powerful.

I have a Server (Windows Server 2003...) and occasionally something happens when a process crashes.  Based on that... I thought maybe I could setup some sort of means for reporting to my email (which coincidently, I get my work email on my phone... so voila..)


Heres what I used..  and its all under 15 lines of code... some good potential here

----------------------------
$FROM = "SERVER@work.com"
$TO = "RCUMMINS@WORK.COM" 
$SMTP_Server = "Exchange.Dot.Com"
$smtp = New-Object Net.Mail.SmtpClient($SMTP_Server)
$SUBJECT = "Server Health Report"

$x = Get-EventLog "Application" -EntryType 'Error' -After (Get-Date).addHours(-1) | 
    Where-Object {$_.Source -eq 'Application Hang'}

if($x)
{
    $xx = $x | select TimeGenerated, Message | Out-String
    $smtp.Send($FROM, $TO, $SUBJECT, $xx)
}
---------------------------

So to setup the scheduled task... I just had to do a quick google for the hidden window option...

---------------------------

C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle "Hidden" -Command ".'C:\Path\To\Scripts\Process Checking.ps1'"
---------------------------

That was enjoyable.

No comments:

Post a Comment