DPXone
Lieutenant
- Registriert
- Mai 2009
- Beiträge
- 554
Hi,
hier mal eine (bereits alte und öfters ausgebaute) PowerShell Funktion für die erweiterte Ausgabe des Eventviewer-Logfiles von mir.
Damit lassen sich alle Einträge in jedem Log-Provider abrufen.
Das erspart einiges an manueller Suche im Eventviewer, wenn man sich auf die Suche auf Microsoft-spezifische Fehler macht, die sich in allen möglichen "Unterordner" der Anwendungslogs von Microsoft befinden können.
Hier hab ich bereits ein Help-Text auf Englisch eingebaut. Multilingual geht leider nicht so einfach.
PowerShell-Events werden im Script standardmäßig unterdrückt, sonst sprengt das den Umfang, da das Script/die Funktion selbst PowerShell-Events auslöst
Beispiele finden sich unter EXAMPLE im Synopsis-Bereich oder, wie gewohnt, über Get-Help Get-EventLog2 -Full, wenn es als Modul (*.psm1) geladen wurde.
Get-EventLog2 | Ogv ohne Parameter gibt z. B. alle Events der letzten Stunde, die den Status: Warnung, Fehler oder Kritisch haben, in einem GridView aus.
UPDATE 2017-12-21:
- $EventLogLevelInt für die Variablen-Deklaration/Wertzuordnung der EventLogLevel als Integer hinzugefügt, um die Variablen-Zuordnung pro ForEach-Step zu ersetzen. (=>minimale Ausführungszeit-Ersparnis)
hier mal eine (bereits alte und öfters ausgebaute) PowerShell Funktion für die erweiterte Ausgabe des Eventviewer-Logfiles von mir.
Damit lassen sich alle Einträge in jedem Log-Provider abrufen.
Das erspart einiges an manueller Suche im Eventviewer, wenn man sich auf die Suche auf Microsoft-spezifische Fehler macht, die sich in allen möglichen "Unterordner" der Anwendungslogs von Microsoft befinden können.
Hier hab ich bereits ein Help-Text auf Englisch eingebaut. Multilingual geht leider nicht so einfach.
PowerShell-Events werden im Script standardmäßig unterdrückt, sonst sprengt das den Umfang, da das Script/die Funktion selbst PowerShell-Events auslöst
Beispiele finden sich unter EXAMPLE im Synopsis-Bereich oder, wie gewohnt, über Get-Help Get-EventLog2 -Full, wenn es als Modul (*.psm1) geladen wurde.
Get-EventLog2 | Ogv ohne Parameter gibt z. B. alle Events der letzten Stunde, die den Status: Warnung, Fehler oder Kritisch haben, in einem GridView aus.
PowerShell:
###############################################################################################################################################################################
# Requirements:
# At least Windows PowerShell 3.0 is required to execute the function. Windows PowerShell is part of the Windows Management Framework (WMF).
# To obtain the latest version as of 12.2017, please install Windows Management Framework (WMF) 5.1 -> https://www.microsoft.com/en-us/download/details.aspx?id=54616
#
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# !!! WARNING: Do not install WMF 5.0 or 5.1 on server providing Microsoft Exchange Services!
# !!! Be also carefully with other Microsoft Server Services!
# !!!
# !!! Please check Product Compatibility of WMF 5.0 and 5.1 with other Microsoft Products:
# !!! WMF 5.0 -> https://docs.microsoft.com/en-us/powershell/wmf/5.0/productincompat
# !!! WMF 5.1 -> https://docs.microsoft.com/en-us/powershell/wmf/5.1/productincompat
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#
# Check current version:
# To check which version is already installed on your Windows system,
# please enter the following built-in PowerShell environment variable in a PowerShell console (do not enter the '#', it's just a comment char):
#
# $PSVersionTable
#
# You should get some version numbers for protocols, assemblies, frameworks, ... used by PowerShell.
# Check the "PSVersion".
#
###############################################################################################################################################################################
#Requires -Version 3.0
Add-Type -TypeDefinition @'
public enum EventLogLevel
{
L0_Undefined,
L1_Critical,
L2_Error,
L3_Warning,
L4_Information,
L5_Verbose
}
'@
Function Get-EventLog2 {
<#
.SYNOPSIS
Get events of all logs.
.DESCRIPTION
Get events of all logs on your local machine.
Events of the 'PowerShell'-Eventlog-Providers are not listed by default!
=================================================================
Warning:
=================================================================
Be careful with the timespan between $StartTime and $EndTime because of performance issues!
.PARAMETER EventLogLevel
Enumerable values:
L0_Undefined = Indicates logs for an undefined message (=> is also shown as Level "Information" in Eventviewer but with log level 0).
L1_Critical = Indicates logs for a critical alert.
L2_Error = Indicates logs for an error.
L3_Warning = Indicates logs for a warning.
L4_Information = Indicates logs for an informational message.
L5_Verbose = Indicates logs for a verbose message.
Default = L1_Critical , L2_Error , L3_Warning
.PARAMETER StartTime
Date and time filter for the desired events.
StartTime defines the start point for which the events should be gathered.
Default = ( ( Get-Date ) - ( New-TimeSpan -Hours 1 ) )
.PARAMETER EndTime
Date and time filter for the desired events.
EndTime defines the end point for which the events should be gathered.
Default = ( Get-Date )
.PARAMETER GroupMessages
Group identical messages for a better overview with an additional counter column.
.PARAMETER OutClipBoardBySystemListSeparator
Output the result directly to the clipboard in a separated format.
The list separator character used depends on the current system settings (see Control Panel -> Region -> Additional Settings)
Can be used to paste the results directly in a Microsoft Excel Worksheet for example.
.PARAMETER IncludePowerShellLogs
Include the PowerShell log events.
By default, all PowerShell events are excluded as many of them are raised by the script execution itself.
.PARAMETER ProviderNameFilter
Filter by Eventlog Provider Names.
Wildcards * (matches zero or more characters) and ? (matches exactly one character) are allowed.
ProviderNameFilter Examples:
"Microsoft-Windows-Winlogon"
"Microsoft-Windows*"
"Microsoft-Windows-*logon"
"Microsoft-???????-????????"
Any * or ? in the filter which should not be used as wildcard has to be escapded by using a backslash!
e. g.
* -> \*
? -> \?
.PARAMETER MessageFilter
Filter by Message content.
Wildcards * (matches zero or more characters) and ? (matches exactly one character) are allowed.
MessageFilter Examples:
"*Application error*"
"Name resolution for the name*"
"*did not register with DCOM within the required timeout."
Any * or ? in the filter which should not be used as wildcard has to be escapded by using a backslash!
* -> \*
? -> \?
.PARAMETER EventIDFilter
Filter by Event ID.
Wildcards * (matches zero or more characters) and ? (matches exactly one character) are allowed.
EventIDFilter Examples:
"100"
"17*"
"*45"
Any * or ? in the filter which should not be used as wildcard has to be escapded by using a backslash!
* -> \*
? -> \?
.EXAMPLE
PS C:\> Get-EventLog2 | Format-Table -AutoSize -Wrap | Out-String -Width 4096
List all 'critical', 'error' and 'warning' events (=default) which occurred in the last hour (=default)
and show the results as string in an autosized and wrapped table.
.EXAMPLE
PS C:\> Get-EventLog2 -Levels (L1_Critical , L2_Error , L3_Warning) -StartTime (( Get-Date ) - ( New-TimeSpan -Hours 1 )) -EndTime (Get-Date) -GroupMessages | Out-GridView
List all 'critical', 'error' and 'warning' events which occurred in the last hour,
group it by messages and show the results in a gridview.
.EXAMPLE
PS C:\> Get-EventLog2 -OutClipBoardBySystemListSeparator
List all 'critical', 'error' and 'warning' (=default) events which occurred in the last hour (=default)
and output the result directly to the clipboard for pasting it to other application e. g. Notepad or Excel.
.EXAMPLE
PS C:\> Get-EventLog2 -MessageFilter 'Name resolution for the name*'
List all 'critical', 'error' and 'warning' (=default) events which occurred in the last hour (=default)
filtered by a regular expression created out of the filter 'Name resolution for the name*' (includes all Event Messages starting with the mentioned string followed by any characters (unlimited)).
.EXAMPLE
PS C:\> Get-EventLog2 -EventIDFilter '10?'
List all 'critical', 'error' and 'warning' (=default) events which occurred in the last hour (=default),
filtered by a regular expression created out of the filter '10?' (includes all Event IDs starting with 10 and with exactly one additional character).
.EXAMPLE
PS C:\> Get-EventLog2 -ProviderNameFilter 'Microsoft-Windows-GroupPolicy'
List all 'critical', 'error' and 'warning' (=default) events which occurred in the last hour (=default)
filtered by a regular expression created out of the filter 'Microsoft-Windows-GroupPolicy' (includes all Events of the mentioned Event Provider).
.NOTES
Created by DPXone on 2016-04-15
Last modified by DPXone on 2017-12-21
Published on: https://www.computerbase.de/forum/threads/powershell-get-eventlog2-sehr-erweiterte-variante-fuer-die-eventlog-ausgabe.1734277/
#>
[CmdletBinding()]
Param (
[Alias('L')]
[EventLogLevel[]] $EventLogLevel = @([EventLogLevel]::L1_Critical ,[EventLogLevel]::L2_Error ,[EventLogLevel]::L3_Warning) ,
[Alias('ST')]
[datetime] $StartTime = (Get-Date) - (New-TimeSpan -Hours 1) ,
[Alias('ET')]
[datetime] $EndTime = (Get-Date) ,
[Alias('G')]
[switch] $GroupMessages = $false ,
[Alias('CB')]
[switch] $OutClipBoardBySystemListSeparator = $false ,
[Alias('IP')]
[switch] $IncludePowerShellLogs = $false ,
[Alias('PF')]
[ValidateNotNullOrEmpty()]
[string[]] $ProviderNameFilter = '*' ,
[Alias('MF')]
[ValidateNotNullOrEmpty()]
[string[]] $MessageFilter = '*' ,
[Alias('IDF')]
[ValidateNotNullOrEmpty()]
[string[]] $EventIDFilter = '*'
)
Begin {
$Events = @()
$objCol = @()
$ListSeparator = (Get-Culture).TextInfo.ListSeparator
$EventLogLevelInt = $EventLogLevel | % {[int] $_ }
Function Create-WildcardAdjustedRegexTerm([string[]] $InputString) {
$Result = @()
$WildcardCharacters = @{
EscapedAsteriskWildcard = @{ Original = '*' ; Escaped = '\*' ; Regex = '.*' ; TemporaryEscapeCharacter = '#%EscapedAstersik%#' }
EscapedMatchOneWildcard = @{ Original = '?' ; Escaped = '\?' ; Regex = '.' ; TemporaryEscapeCharacter = '#%EscapedMatchOne%#' }
}
$Exclusions = @{
DotExclusion = @{ Original = '.' ; Escaped = '\.' }
DollarExclusion = @{ Original = '$' ; Escaped = '\$' }
CircumflexExclusion = @{ Original = '^' ; Escaped = '\^' }
PlusExclusion = @{ Original = '+' ; Escaped = '\+' }
}
Foreach ($InputStr In $InputString) {
$FilterString = $InputStr
# Exclude other characters (e.g. dot)
$FilterString = $FilterString.replace($Exclusions.DotExclusion.Original , $Exclusions.DotExclusion.Escaped)
$FilterString = $FilterString.replace($Exclusions.DollarExclusion.Original , $Exclusions.DollarExclusion.Escaped)
$FilterString = $FilterString.replace($Exclusions.CircumflexExclusion.Original , $Exclusions.CircumflexExclusion.Escaped)
$FilterString = $FilterString.replace($Exclusions.PlusExclusion.Original , $Exclusions.PlusExclusion.Escaped)
# Change wildcard characters
$FilterString = $FilterString.replace($WildcardCharacters.EscapedAsteriskWildcard.Escaped , $WildcardCharacters.EscapedAsteriskWildcard.TemporaryEscapeCharacter)
$FilterString = $FilterString.replace($WildcardCharacters.EscapedMatchOneWildcard.Escaped , $WildcardCharacters.EscapedMatchOneWildcard.TemporaryEscapeCharacter)
$FilterString = $FilterString.split($WildcardCharacters.EscapedAsteriskWildcard.Original)
$FilterString = "(" + ($FilterString -join ")$($WildcardCharacters.EscapedAsteriskWildcard.Regex)(") + ")"
$FilterString = $FilterString.Split($WildcardCharacters.EscapedMatchOneWildcard.Original)
$FilterString = "(" + ($FilterString -join ")$($WildcardCharacters.EscapedMatchOneWildcard.Regex)(") + ")"
$FilterString = $FilterString.replace($WildcardCharacters.EscapedAsteriskWildcard.TemporaryEscapeCharacter , $WildcardCharacters.EscapedAsteriskWildcard.Escaped)
$FilterString = $FilterString.replace($WildcardCharacters.EscapedMatchOneWildcard.TemporaryEscapeCharacter , $WildcardCharacters.EscapedMatchOneWildcard.Escaped)
$Result+= "($FilterString)"
}
Return $Result -join "|"
}
$ProviderNameRegexFilter = Create-WildcardAdjustedRegexTerm $ProviderNameFilter
$EventIDRegexFilter = Create-WildcardAdjustedRegexTerm $EventIDFilter
$MessageRegexFilter = Create-WildcardAdjustedRegexTerm $MessageFilter
write-Verbose("{0,-25}: {1}" -f 'StartTime filter' , $StartTime)
write-Verbose("{0,-25}: {1}" -f 'EndTime filter' , $EndTime)
write-Verbose("{0,-25}: {1}" -f 'Levels' ,($EventLogLevel -join ', '))
write-Verbose("{0,-25}: {1}" -f 'GroupMessages' , $GroupMessages)
write-Verbose("{0,-25}: {1}" -f 'IncludePowerShellLogs' , $IncludePowerShellLogs -join ', ')
write-Verbose("{0,-25}: {1}" -f "ProviderNameRegexFilter" , $ProviderNameRegexFilter)
write-Verbose("{0,-25}: {1}" -f "EventIDRegexFilter" , $EventIDRegexFilter)
write-Verbose("{0,-25}: {1}" -f "MessageRegexFilter" , $MessageRegexFilter)
}
Process {
$Logs = Get-WinEvent -ListLog * -ErrorAction Ignore
Foreach ($Log In $Logs) {
$hash = @{ LogName = $Log.LogName ; Level = $EventLogLevelInt ; StartTime = $StartTime ; EndTime = $EndTime }
$tempEvents = Get-WinEvent -FilterHashtable $hash -ErrorAction Ignore
If ($tempEvents) {
$Events+= $tempEvents
}
$tempEvents = $null
}
If ($GroupMessages) {
$GroupedEvents = ($Events | Group-Object Message)
Foreach ($Group In $GroupedEvents) {
$obj = New-Object psobject $Group.Group[0]
$obj | Add-Member NoteProperty -Name 'Count' -value $Group.count
$objCol+= $obj
}
$Events = $objCol
}
}
End {
$props = 'TimeCreated' , 'LevelDisplayName' , 'ProviderName' , @{ n = 'ID' ; e = {[string] $_.'ID' } } , 'TaskDisplayName' , 'Message'
If ($GroupMessages) { $props+= 'Count' }
$Out = $Events | sort TimeCreated -d | Select $props | ? {([regex]::IsMatch($_.ProviderName , $ProviderNameRegexFilter)) -and
([regex]::IsMatch($_.ID , $EventIDRegexFilter)) -and ([regex]::IsMatch($_.Message , $MessageRegexFilter ,[System.Text.RegularExpressions.RegexOptions]::Multiline)) }
If (-not $IncludePowerShellLogs) {
$Out = $Out | ? { $_.ProviderName -notlike '*PowerShell*' }
}
If ($OutClipBoardBySystemListSeparator) {
$Out | ConvertTo-Csv -Delimiter $ListSeparator -NoTypeInformation | Set-Clipboard
} Else {
$Out
}
}
}
UPDATE 2017-12-21:
- Help-Text nun vollständig und für einige Parameter geändert.
- Weitere Beispiele angefügt
- Anforderungen zur Ausführung + Warnung für Microsoft Server Produkte als Kommentar eingefügt
- "EventLogLevel" als Enumeration eingebaut (Pre-PowerShell 5.0 kompatibel durch TypeDefinition)
- Funktion zur Erstellung von RegEx-Pattern komplett überarbeitet
- $Levels umbenannt zu $EventLogLevel
- [ValidateNotNullOrEmpty()] für die Filter eingebaut. (Die anderen Parameter können aufgrund der Deklaration gar nicht $null oder $empty sein)
- $EventLogLevelInt für die Variablen-Deklaration/Wertzuordnung der EventLogLevel als Integer hinzugefügt, um die Variablen-Zuordnung pro ForEach-Step zu ersetzen. (=>minimale Ausführungszeit-Ersparnis)
Zuletzt bearbeitet: