stephanlinke

[PRTG] Get Windows Events

Dec 3rd, 2015
284
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #___ ___ _____ ___
  2. #| _ \ _ \_   _/ __|
  3. #|  _/   / | || (_ |
  4. #|_| |_|_\ |_| \___|
  5. #    NETWORK MONITOR
  6. #-------------------
  7. #(c) 2014 Stephan Linke, Paessler AG
  8. <#
  9.    .SYNOPSIS
  10.    Reads the windows eventlog and filters for the specified events.
  11.  
  12.    .DESCRIPTION
  13.    This custom sensor for PRTG will read the given EventLog file and search it
  14.    for the defined events. It also allows to error if the last event found has a certain ID or
  15.    Message. Make sure you set "Use credentials of parent device" in the sensors security settings".
  16.  
  17.    .PARAMETER ComputerName
  18.    The computer whose event log you want to check
  19.      
  20.    .PARAMETER Channel
  21.    The log name that is used by the application  
  22.    
  23.    .PARAMETER ProviderName
  24.    The application that you want to watch
  25.  
  26.    .PARAMETER Levels
  27.    The Loglevels you want to include in the search
  28.  
  29.    .PARAMETER EventID
  30.    The event IDs you want to filter. Seperate multiple IDs with comma
  31.    
  32.    .PARAMETER EnableExceptId
  33.    This will allow you to enter a number of (or none) event Ids to ignore (i.e. remove from the list after retrieving them) as EventIDs.
  34.    Those IDs will not be considered for the sensor state! If you want to do so, simply use the -EnableExceptId switch upon calling the script.
  35.  
  36.    .PARAMETER WarningEvents
  37.    The event IDs you want to raise a warning when found. Those IDs also have to be included in the event ids
  38.  
  39.    .PARAMETER ErrorEvents
  40.    The event IDs you want to raise a error when found. Those IDs also have to be included in the event ids
  41.  
  42.    .PARAMETER MaxAge
  43.    The age of the Logfile in hours
  44.    
  45.    .PARAMETER LimitEntries
  46.    Maximum number of log entries to be checked (order is new -> old)
  47.  
  48.    .PARAMETER StateBasedOnLastID
  49.    If this parameter is set, not the sheer number of events will decide if the sensor will go into error or warning state,
  50.    but only the event id of the last entry found. This is useful for RAID controllers, etc.
  51.  
  52.    .PARAMETER StateBasedOnLastMessage
  53.    If this parameter is set, not the sheer number of events will decide if the sensor will go into error or warning state,
  54.    but only the message of the last entry found. This is useful if messages have the same event ID for errors and information events.
  55.    
  56.    .OUTPUTS
  57.    <number of entries found>:<entries> found in the event log. Last message: <last entry message>
  58.  
  59.    .EXAMPLE
  60.    C:\PS> .\Get-Events.ps1  -ComputerName %host -Username "%windowsdomain\%windowsuser" -Password "%windowspassword" -ProviderName "Microsoft-Windows-Immersive-Shell" -Channel "Microsoft-Windows-TWinUI/Operational" -LimitEntries 1 -MaxAge 1 -EventID 1719 -Level 4
  61.  
  62.    .EXAMPLE
  63.    C:\PS> .\Get-Events.ps1  -ComputerName %host -Username "%windowsdomain\%windowsuser" -Password "%windowspassword" -ProviderName "Microsoft-Windows-Immersive-Shell" -Channel "Microsoft-Windows-TWinUI/Operational" -LimitEntries 1 -MaxAge 1 -EventID 1719 -Level 4 -StateBasedOnLastEntry
  64. #>
  65.  
  66. #region Requirements
  67. #Requires -Version 3.0
  68. #endregion
  69.  
  70. param(
  71.     [string]$ComputerName   = "",
  72.     [string[]]$Channel      = @(""),
  73.     [string[]]$ProviderName = @(""),
  74.     [int[]]$EventID         = @(),
  75.     [switch]$EnableExceptID   = $False,
  76.     [switch]$EnableExceptChannel = $False,
  77.     [switch]$EnableExceptProvider= $False,
  78.     [int[]]$WarningEvents   = @(),
  79.     [int[]]$ErrorEvents     = @(),
  80.     [string[]]$ErrorStrings = @(),
  81.     [string[]]$WarningStrings = @(),
  82.     [int[]]$Levels          = @(2),
  83.     [float]$MaxAge          = 20,
  84.     [int]$LimitEntries      = 10,
  85.     [switch]$AlwaysShowMessage,
  86.     [switch]$StateBasedOnLastMessage,
  87.     [switch]$StateBasedOnLastEventID
  88. )
  89. [System.Threading.Thread]::CurrentThread.CurrentCulture = New-Object "System.Globalization.CultureInfo" "en-US"
  90. $ExitCode = 0
  91. $Message = ""
  92.  
  93. # This will retrieve the event log entries
  94. # based on channel, provider and events ID.
  95. #######################################
  96. function readEventLog(){
  97.     ## create an eventfilter object array for the
  98.    
  99.     if(!($EnableExceptID)){
  100.         $EventFilter = @{
  101.             ProviderName=$ProviderName;
  102.             LogName=$Channel;
  103.             ID=$EventID;
  104.             Level=$Levels;
  105.             StartTime=(get-date).AddHours(-$MaxAge)
  106.         }
  107.     }
  108.  
  109.     else{
  110.     $EventFilter = @{
  111.             ProviderName=$ProviderName;
  112.             LogName=$Channel;
  113.             Level=$Levels;
  114.             StartTime=(get-date).AddHours(-$MaxAge)
  115.         }
  116.     }
  117.  
  118.     if($EnableExceptChannel){
  119.             $Events = ($Events | Where { $Channel -notcontains $_.LogName });
  120.         }
  121.     if($EnableExceptProvider){
  122.             $Events = ($Events | Where { $ProviderName -notcontains $_.ProviderName });
  123.         }
  124.  
  125.  
  126.     try{
  127.         $Events = (Get-WinEvent -ComputerName $ComputerName -FilterHashTable $EventFilter -MaxEvents $LimitEntries -EA silentlycontinue)
  128.        
  129.         if($EnableExceptID){
  130.             $Events = ($Events | Where { $EventID -notcontains $_.Id });
  131.         }
  132.  
  133.         return $Events;
  134.     }
  135.     catch [Exception]{
  136.         Write-Host "0:Can't find anything for $ProviderName in your $Channel eventlog. Please check Log name, Provider, Log ID, EventID, ComputerName and Credentials"
  137.         Write-Host $_.Exception.Message
  138.         Exit 2;
  139.     }
  140. }
  141.  
  142. # This will evaluate the results from the above
  143. # function and return the sensor value
  144. #######################################
  145. function evaluateLogResults(){
  146.        
  147.         $Events = (readEventLog);
  148.         $Counter = $Events.Count
  149.  
  150.         # Always show the last message when enabled
  151.         if(($AlwaysShowMessage) -and ($Counter -ne 0)){
  152.         $LastMessage = ($Events[0].Message.Remove($Events[0].Message.Length / 6)+"..." -replace "`n|`r")
  153.         $Message = "(Last entry: "+$LastMessage+")"
  154.         }
  155.                
  156.         # Search for error and warning IDs
  157.         if(($Counter -ne 0) -and (($StateBasedOnLastEventID)) -and (-not($StateBasedOnLastMessage))){
  158.                 switch ($Events[0].Id){
  159.                     {$ErrorEvents -contains $Events[0].Id}{ Write-Host $Counter":Critical event found: $($Message)"; $ExitCode = 2; return}
  160.                     {$WarningEvents -contains $Events[0].Id}{ Write-Host $Counter":Warning event found: $($Message)"; $ExitCode = 1; return}
  161.                 }
  162.         }
  163.        
  164.         # Search for messages that contain the error and warning strings
  165.         elseif(($Counter -ne 0) -and ($StateBasedOnLastMessage)){
  166.         foreach($String in $ErrorStrings){
  167.                     if($Events[0].Message -match "($String)"){ Write-Host ("{0}:Critical event found: {1}" -f $Counter,$Message); $ExitCode = 2; return; } }
  168.                 foreach($String in $WarningStrings){
  169.                     if($Events[0].Message -match "($String)"){ Write-Host ("{0}:Warning event found: {1}" -f $Counter,$Message); $ExitCode = 2; return; } }
  170.         }
  171.    
  172.         # Search for messages that contain the error and warning strings and make the state message based
  173.         elseif(($Counter -ne 0) -and (($StateBasedOnLastMessage) -and ($StateBasedOnLastID))){
  174.         switch ($Events[0].Id){
  175.                     {($ErrorEvents -contains $Events[0].Id) -and ($Events[0].Message -match $ErrorStrings)} {
  176.                         Write-Host ("{0}:Critical event found: {1}" -f $Counter,$Message); $ExitCode = 1; return}
  177.                     {($WarningEvents -contains $Events[0].Id) -and ($Events[0].Message -match $WarningStrings)} {
  178.                         Write-Host ("{0}:Warning event found: {1}" -f $Counter,$Message); $ExitCode = 2; return}
  179.                     }
  180.         }
  181.  
  182.         switch ($Counter){
  183.                 {$Counter -eq 0}{ Write-Host ("{0}:No log entries found" -f $Counter); $ExitCode = 0; return }
  184.                 {$Counter -eq 1}{ Write-Host ("{0}:{0} log entry found in the last {1} hours {2}" -f $Counter, $MaxAge, $Message); $ExitCode = 0; return; }
  185.                 {$Counter -gt 1}{ Write-Host ("{0}:{0} log entries found in the last {1} hours {2}" -f $Counter, $MaxAge, $Message); $ExitCode = 0; return; }
  186.             }
  187.            
  188. }
  189.  
  190. # Action!
  191. evaluateLogResults;
  192. exit $ExitCode;
Advertisement
Add Comment
Please, Sign In to add comment