Archive for June, 2011

PowerShell Profile Microsoft.PowerShell_profile.ps1

Notes:
This is my current profile, it is very simple at the moment.

function prompt {
    $cwd = (get-location).Path

    [array]$cwdt=$()
    $cwdi=-1
    do {
        $cwdi=$cwd.indexofany(”\\”,$cwdi+1)
        [array]$cwdt+=$cwdi} until($cwdi -eq -1)

        if ($cwdt.count -gt 3) {
            $cwd = $cwd.substring(0,$cwdt[0]) + “\..” + $cwd.substring($cwdt[$cwdt.count-3])
    }

    ” $cwd>_ ”
}
# The above sets prompt to the current drive letter, immediate sub directory and current directory.
#     Example: C:\..\drivers\etc>_ 

Import-Module Pscx #-arg ~\Pscx.UserPreferences.ps1

PowerShell Script Watch-EventLogs.ps1

Project Objective:
Monitor event logs with script that can be deployed in a multiple scenarios.

Problem to be solved:
A few of the existing Nagios scripts or commands that have similar functionality either do not provide the verbose output that this script has or they do have an expectable method for adding exceptions.

Future Versions:
I’d like to add the SMTP auth ability. I’m also considering an all in one Application, System log script.

Notes:
This script is not limited to the Application and System logs, you can use it to check any Windows event log. Note that I changed the verb from Test to Watch. I think Watch better fits the description, I may go back and change other scripts to reflect this.

#
# Watch-EventLogs.ps1
#
# Written by Aaron Wurthmann (aaron (AT) wurthmann (DOT) com)
#
# If you edit please keep my name as an original author and
# keep me apprised of the changes, see email address above.
# This code may not be used for commercial purposes.
# You the executor, runner, user accept all liability.
# This code comes with ABSOLUTELY NO WARRANTY.
# You may redistribute copies of the code under the terms of the GPL v2.
# -----------------------------------------------------------------------
# 2011.06.27 ver 1.7
#
# Summary:
# Checks for recent* Warning and Error messages in the System OR Applicaiton event logs.
# Default checks System logs, use -logname Application, to check Application logs
#
# *Recent: Uses registry key to determine when the last check was made.
# -----------------------------------------------------------------------
# General Usage:
#    This script can be edited and or parameters can be passed to enable
#    email alerts, to whom, from whom, using what server, etc.
#     Examples:    
#        .\Watch-EventLogs.ps1 -Logname Application
#        .\Watch-EventLogs.ps1 -Logname System
#        .\Watch-EventLogs.ps1 -email True -From foobar@null.local -To administrator@null.local -Server smtp.null.local
#
# Scheduled Task Usage
#    To run this script as a scheduled task create a .bat .cmd file
#    As indicated above you can either pass the needed parameters or
#    edit Watch-EventLogs.ps1 itself. 
#    Example of .bat or .cmd file:
#        powershell -command "& '.\Watch-EventLogs.ps1' -email True -From foobar@null.local -To administrator@null.local -Server smtp.null.local"
#
# Nagios Usage:
#    For Nagios NRPE/NSClient++ usage add the following line to the 
#    NSC.ini file after placing this script in Scripts subdirectory.
#    check_sysevents=cmd /c echo scripts\Watch-EventLogs.ps1; exit($lastexitcode) | powershell.exe -command -
#    check_appevents=cmd /c echo scripts\Watch-EventLogs.ps1 -logname Application; exit($lastexitcode) | powershell.exe -command -
#    NOTE: The trailing - is required.
# -----------------------------------------------------------------------
# Notes:
#    At the moment there is no error detection built in for the email send.
#    There is also no smpt auth. I'll put that in at a later time.
# -----------------------------------------------------------------------

# Parameters and Editable Settings
Param(
    [int]$ResultWarning = 0,
    [int]$ResultError = 0,
    [string]$From = "noreply@domain.ext",
    [string]$To = "someone@domain.ext",
    [string]$Server = "smtp.domain.ext",
    [string]$Logname = "System",
    $email=$false
)

$IgnoreSources=@(
    'Print',
    'DnsApi',
    'Some Source',
    'Some other Source';
)

$IgnoreEvendID=@(
    '42424242',
    '69696969';
)
# End Editable Section


[string]$computername=$env:computername 
$RegKey='HKLM:\SYSTEM\CurrentControlSet\Services\NRPE_NT'
$RegEntry=$Logname+'_Log_Check'
$Date=Get-Date

if(!(Test-Path $RegKey)) {New-Item -Path $RegKey}
$NRPE=Get-ItemProperty -Path $RegKey
if (!($NRPE.$RegEntry)) {
    $CreateRegEntry=New-ItemProperty -Path $RegKey -Name $RegEntry -PropertyType String -Value $Date
    if ($CreateRegEntry) {
        $NRPE=Get-ItemProperty -Path $RegKey
    }
    ELSE {
        write-host 'FATAL ERROR:' $RegKey'\'$RegEntry 'was not created.'
        exit 2
        
    }
}
$ExecDate=$NRPE.$RegEntry

$Properties='EntryType','Message','Source','TimeWritten','EventID'
$LogEntries=Get-EventLog -Logname $Logname -EntryType Error,Warning -After $ExecDate | 
    Where {$IgnoreSources -notcontains $_.Source -and $IgnoreEvendID -notcontains $_.EventID} | 
    Select-Object -Property $Properties

$Date=Get-Date
Set-ItemProperty -Path $RegKey -Name $RegEntry -Value $Date
    
if ($LogEntries) {
    ForEach ($LogEntry in $LogEntries) {
        $EntryType=$LogEntry.EntryType.ToString()
        $Message=$LogEntry.Message.Substring(0,76).TrimEnd().ToString()+'...'
        $Source=$LogEntry.Source.ToString()
        $TimeWritten=$LogEntry.TimeWritten.ToString()
        $EventID=$LogEntry.EventID.ToString()
         
         
        if ($EntryType -eq 'Error') {
            $ResultError=2
            if ($CriticalResults) {
                $CriticalResults=@"
$EntryType 
Event ID: $EventID
$Message
Source: $Source
At: $TimeWritten

$CriticalResults
"@
            }
            ELSE {
                $CriticalResults = @"
$EntryType
Event ID: $EventID 
$Message
Source: $Source
At: $TimeWritten
"@
            }
        }
        ELSE {
            if ($EntryType -eq 'Warning') {
                $ResultWarning=1
                if ($WarningResults) {
                    $WarningResults=@"
$EntryType
Event ID: $EventID 
$Message
Source: $Source
At: $TimeWritten

$WarningResults
"@
                }
                ELSE {
                    $WarningResults = @"
$EntryType
Event ID: $EventID 
$Message
Source: $Source
At: $TimeWritten
"@
                }
            }
        }
    }
}

if ($email) {
    $msg = new-object Net.Mail.MailMessage
    $smtp = new-object Net.Mail.SmtpClient($Server)
    $msg.From = $From
    $msg.To.Add($To)
}

[int]$ResultTotal=$ResultWarning + $ResultError
$Results= @"
$Logname Entries:

$CriticalResults

$WarningResults
"@

Switch ($ResultTotal) {
    default {
        write-host 'No Errors or Warnings were found in the' $Logname 'event logs as of' $Date
        exit 0
    }

    1 {
        write-host $Results
        if ($email) {
            $msg.Subject = 'WARNING: Warning messages were found in the ' +$Logname+ ' event logs on ' + $computername + ' at ' + $Date
            $msg.Body = $Results
            $smtp.Send($msg)
        }
        exit 1
    }

    2 {
        write-host $Results
        if ($email) {
            $msg.Subject = 'CRITICAL: Error messages were found in the ' +$Logname+ ' event logs on ' + $computername + ' at ' + $Date
            $msg.Body = $Results
            $smtp.Send($msg)
        }
        exit 2
    } 

    3 {
        write-host $Results
        if ($email) {
            $msg.Subject = 'CRITICAL: Error and Warning messages were found in the ' +$Logname+ ' event logs on ' + $computername + ' at ' + $Date
            $msg.Body = $Results
            $smtp.Send($msg)
        }
        exit 2
    } 
}