Contact Info

Crumbtrail

ActiveXperts.com » Network Monitor » Scripts » Custom Script

eventlog.ps1 - powershell script by ActiveXperts Software

eventlog.ps1 checks whether certain events exist in a Event Log.

Use eventlog.ps1 directly from ActiveXperts Network Monitor; in the Manager's 'Monitor' menu, select 'New Check (Script)' and select eventlog.ps1. Configure the required parameter, or press 'Load a working sample'.

In ActiveXperts Network Monitor, Administrators can use three different scripting languages: Powershell, VBScript and SSH.


eventlog.ps1 script code

#################################################################################
# ActiveXperts Network Monitor PowerShell script, © ActiveXperts Software B.V.
# For more information about ActiveXperts Network Monitor, visit the ActiveXperts 
# Network Monitor web site at http://www.activexperts.com
#################################################################################
# Script
#      EventLog.ps1
# Description:
#     Checks if an event is present into the EventLog
# Declare Parameters:
#     1) strHost (string) - Hostname or IP address of the computer you want to ping
#     2) strEvtLogFile (string) - Name of the Logfile, for instance: Application
#     3) strEventID (string) - EventCode, for instance: '8000'. Use the '*' wildcard to select all
#     4) strEvtSource (string) - Name of the Source, for instance ''AxNmSvc'. Use the '*' wildcard to select all
#     5) strEvtDescriptionPattern (string)- Pattern to match in the description. Use the '*' wildcard to select all
#     6) bErrorWhenFound (string) - When 1 or more events are matched, result is: Error or Success
#     7) strAltCredentials (string, optional) - Specify an empty string to use Network Monitor service credentials.
#         To use alternate credentials, enter a server that is defined in Server Credentials table.
#         (To define Server Credentials, choose Tools->Options->Server Credentials)
# Usage:
#      .\EventLog.ps1 '<Hostname | IP>' '<Application | System | ...>' <event_id> '<Source Name>' '<Pattern>' '<$true | $false>
# Sample:
#      .\EventLog.ps1 'localhost' 'application' '1' 'AxNmSvc' 'ActiveXperts Network Monitor' '$false'
#
# This function uses of the 'ActiveXperts.NMWev' ActiveX control to access Windows .evt and .evtx Event Logs on remote computers. 
# The control simplifies the XPath programming logic, by providing easy-to-use functions to access event logs.
# ActiveXperts.NMWev data members:
#  - LastError. Use it to check the result of a function. After a call to a function, LastError will be 0 for success, or else a positive error code.
#    Error codes can be lookup up here: http://www.activexperts.com/support/errorcodes/
# ActiveXperts.NMWev functions:
#  - Initialize( LogFile As String ). Initializes the 'ActiveXperts.NMWev' object. Pass a valid log filename for troubleshooting purposes/
#  - Shutdown(). Call it to unintialize the object. Should always be called at the end of the script.
#  - Clear(). Clears the LastError property of the object.
#  - BuildQuery( EventLog As String, FilterSource As String, FilterEventID As String, FilterTaskCategory As String, FilterUser As String, FilterData As String, LevelFlags As Number, TimeSpanMilliseconds As Number )
#     Function returns an XPath string that can be used in FindFirstEvent's first parameter.
#     Use the ActiveXperts Event Log Diagnostic Utility to see how XPath queries are defined. Such XPath string can be simply copy/pasted into this script, instead of using 'BuildQuery'.
#  - GetLevelFlag( Information As Boolean, LevelWarning As Boolean, LevelError As Boolean, LevelCritical As Boolean, LevelVerbose As Boolean, LevelSuccess As Boolean, LevelFailure As Boolean )
#     The function returns a number value that can be used as input parameter to BuildQuery's LevelFlags parameter.
#  - Connect( Host As String, AlternateUser As String, AlternatePassword As String )
#     Establishes a connection to a (remote) host.
#     AlternateUser and AlternatePassword should only be set in case alternate credentials should be used.
#  - Disconnect
#     Disconnects the connected session.
#  - FindFirstEvent( XPathQuery As String, MatchDescription As String, MatchDescriptionCase As Boolean, MatchDescriptionRegExpression As Boolean )
#     The function returns the first event (As String).
#     Parameter XPathQuery: can be defined by BuildQuery function.
#     Parameter MatchDescription: the description pattern that should be matched, or empty if no pattern matching should be used.
#     Parameter MatchDescriptionCase: if MatchDescription is set, this parameter tells whether or not case senstsitive matching should be performed.
#     Parameter MatchDescriptionRegExpression: if MatchDescription is set, this parameter tells whether or not case regular expressions are used in MatchDescription
#  - FindNextEvent()
#     Retrieves the next event. Should always be called after a successfull call to FindNextEvent.
#################################################################################

# -- Declare Parameters
param( [string]$strHost = '', [string]$strLogName = '', [string]$strEventID = '', [string]$strEvtSource = '', [string]$strEvtDescriptionPattern = '', [string]$bErrorWhenFound = $false, [string]$strAltCredentials = ''  )

# -- Use _activexperts.ps1 with common functions
. 'C:\Program Files\ActiveXperts\Network Monitor\Scripts\Monitor (ps1)\_activexperts.ps1'


#################################################################################
# // --- Main script ---
#################################################################################

# -- Clear screen and clear error
set-psdebug -strict
cls
$Error.Clear()

# -- Validate parameters, return on parameter mismatch
if( $strHost -eq '' -or $strLogName -eq '' -or -$strEventID -eq '' -or $strEvtSource -eq '' -or $strEvtDescriptionPattern -eq '' )
{
  $res = 'UNCERTAIN:  Invalid number of parameters - Usage: .\EventLog.ps1 "<Hostname | IP>" "<Application | System | ...>" "<event_id>" "<Source Name>" "<Pattern>" "<$true | $false>"'
  echo $res
  exit
}

# -- Declare local variables by assigning initial value
$strExplanation = ''
$objAltCredentials = $null
$objNmWev = new-object -comobject ActiveXperts.NMWev

# If alternate credentials are specified, retrieve the alternate login and password from the ActiveXperts global settings
if( $strAltCredentials -ne '' )
{
  # Get the Alternate Credentials object. Function "AxGetCredentials" is implemented in "_activexperts.ps1"
  if( ( AxGetCredentials $strHost  $strAltCredentials ([ref]$objAltCredentials) ([ref]$strExplanation) ) -ne $AXSUCCESS )
  {
    echo $strExplanation
    exit
  }
}
  
# Initialze EventLog object. Optional parameter: a log file, for debugging purposes
$objNmWev.Initialize( '' )

if( $objNmWev.LastError -ne 0 )
{
   $res = 'ERROR: Failed to connect'
   echo $res
   exit
}

if( $strAltCredentials -ne '' )
{
  $objNmWev.Connect( $strHost, $objAltCredentials.Username, $objAltCredentials.Password )
}
else
{
  $objNmWev.Connect( $strHost, '', '' )
}

if( $objNmWev.LastError -ne 0 )
{
   $res = 'ERROR: Failed to connect'
   echo $res
   exit
}

# Get Level Flag. 
#  Param1: Information Events (yes/no)
#  Param2: Warning Events (yes/no)
#  Param3: Error Events (yes/no)
#  Param4: Critical Events (yes/no)
#  Param5: Verbose Events (yes/no)
#  Param6: Success Events (yes/no)
#  Param7: Failure Events (yes/no)
$numLevelFlag = $objNmWev.GetLevelFlag( $true, $true, $true, $true, $true, $true, $true )

# Get Query string. 
#  Param1: Event Log File, e.g. "Application"
#  Param2: Event Source. Use '*' for any source
#  Param3: Event ID. Use '*' for any event ID
#  Param4: Event Category. Use '*' for any event category
$strQuery = $objNmWev.BuildQuery( $strLogName, $strEvtSource, $strEventID, '*', '*', '*', $numLevelFlag , 0 )    

# Get First event
#  Param1: The Query
#  Param2: Description to match. If empty, no description pattern matching will be performed
#  Param3: Description matching case sensitive (yes/no)
#  Param4: Use regular expressions for pattern matching (yes/no)

# NOTE: we're not making use of regular expressions. (change the latter to True if you wish!)
# However, it is nice to have '*' as any description. Let's convert '*' to '' because that's what most people expect.
if( $strEvtDescriptionPattern -eq '*' ) 
{
    strEvtDescriptionPattern = ''
}
$strEvent = $objNmWev.FindFirstEvent( $strQuery, $strEvtDescriptionPattern, $false, $false )

$numEvents = 0
while( $objNmWev.LastError -eq 0 )
{
  $numEvents += 1
  $strEvent = $objNmWev.FindNextEvent()
}

$objNmWev.FindEventClose()

if( $bErrorWhenFound -and ( $numEvents -gt 0 ) )
{
  $res = 'SUCCESS: Events found: [' + $numEvents + ']' + 'DATA:' + $numEvents
}
else
{
  $res = 'ERROR: Events found: [' + $numEvents + ']' + 'DATA:' + $numEvents
}  

# Disconnect
$objNmWev.Disconnect()   

# Uninitialize
$objNmWev.Shutdown()    

echo $res


#################################################################################

trap [Exception]
{
  $res = 'UNCERTAINs: ' + $_.Exception.Message
  echo $res
  exit
}