Check eventlog status in powershell

When we monitor servers, we need to get notified if there are new errors and/or warnings in the Windows Eventlog.. Normally, it is the Application event log we check for these errors and warnings. The required functionality is that the script should check for errors and warnings on the current machine and if the number of event exceeds a maximum, the script should send an email to administrator to notify that some further investigation is needed on the server.

Here is the second powershell script I wrote today:

CHECK_EVENT_LOG_STATISTICS.PS1:

param([String]$logname="Application", [Int]$maxEventCount=10)

$since = ((get-date).addDays(-1));

$errwarnlist =  Get-Eventlog -logname $logname -after $since 
			-EntryType Error, Warning
$linecount = $errwarnlist | Measure-Object –Line

$msg = $env:COMPUTERNAME + " " + $logname + " eventlog has " 
       + $linecount.Lines  
       + " errors/warnings since " + $since.ToString("dd.MM.yyy HH:mm") 
       + ". Limit = " + $maxEventCount;

if ($linecount.Lines -gt $maxEventCount)
{
    $xto = john.doe@company.com
    $xfrom = "no-reply@company.com"
    $xsub = $env:COMPUTERNAME + ": " + $logname 
            + " eventlog exceeds limit for errors/warnings";

    Write-host $msg

    Send-MailMessage -To $xto -From $xfrom  
                 -Subject $xsub  -Body $msg 
                 -SmtpServer smtp.company.com
}
else
{
    Write-host $msg
}
Advertisements

Calculate total and iteration elapsed time in Powershell

When you are executing long-running scripts you probably want to know how long time each part of the script is taking to execute, and the total run time of the script. The demo script below shows how to use the Get-Date and Get-Random CmdLets.

When calculating elapsed time the substraction will result in a TimeSpan database like the one in C#.

$script:startTime = Get-Date

function GetElapsedTime([datetime]$starttime) 
{
    $runtime = $(get-date) - $starttime
    $retStr = [string]::format("{0} sec(s)", $runtime.TotalSeconds)
    $retStr
}

write-host "Script Started at $script:startTime"
for ($i=1; $i -lt 10; $i++) 
{
    $iterTime = Get-Date ;
    get-process | out-null
    $waitsecs = Get-Random -minimum 1 -maximum 5
    sleep $waitsecs
    $elapsed = GetElapsedTime $iterTime ;
    write-host "   Iteration Time: " $elapsed ;
}

write-host "Script Ended at $(get-date)"
$elapsed = GetElapsedTime $script:startTime
write-host "Total Elapsed Time: " $elapsed;

Happy coding…