{"id":353614,"date":"1970-01-01T00:00:00","date_gmt":"1970-01-01T00:00:00","guid":{"rendered":"https:\/\/www.ninjaone.com\/?post_type=script_hub&#038;p=353614"},"modified":"2024-10-29T07:51:18","modified_gmt":"2024-10-29T07:51:18","slug":"powershell-fuer-effiziente-ereignisprotokollsuchen","status":"publish","type":"script_hub","link":"https:\/\/www.ninjaone.com\/de\/script-hub\/powershell-fuer-effiziente-ereignisprotokollsuchen\/","title":{"rendered":"Ausf\u00fchrlicher Guide zur Verwendung von PowerShell f\u00fcr effiziente Ereignisprotokollsuchen"},"content":{"rendered":"<p>In der sich st\u00e4ndig weiterentwickelnden IT-Welt sind das Monitoring und die Analyse von Ereignisprotokollen essenziell f\u00fcr die Aufrechterhaltung des Systemzustands, die Diagnose von Problemen und die Gew\u00e4hrleistung der Sicherheits-Compliance.<\/p>\n<p>Ereignisprotokolle sind eine ergiebige Quelle f\u00fcr Informationen \u00fcber den Zustand und das Verhalten von Systemen, und die M\u00f6glichkeit, diese Protokolle effizient zu durchsuchen und zu filtern, kann die F\u00e4higkeit eines IT-Experten zur Verwaltung seiner Infrastruktur erheblich verbessern.<\/p>\n<p>In diesem Blogbeitrag besprechen wir, wie Sie PowerShell f\u00fcr effiziente Ereignisprotokollsuchen verwenden k\u00f6nnen. Genauer gesagt wird heute ein PowerShell-Skript vorgestellt, das die <strong>Suche in Ereignisprotokollen<\/strong> vereinfacht und das Auffinden bestimmter Ereignisse anhand von Kriterien wie Ereignisprotokollnamen, Quelle, Ereignis-ID usw. erleichtert.<\/p>\n<h2>Die Bedeutung des Ereignisprotokollmanagements in der IT<\/h2>\n<p>Ereignisprotokolle sind Aufzeichnungen von System-, Sicherheits- und Anwendungsereignissen auf einem Computer. Diese Protokolle sind unverzichtbar f\u00fcr die Fehlerbehebung, die \u00dcberpr\u00fcfung von Sicherheitsvorf\u00e4llen und die Compliance.<\/p>\n<p>F\u00fcr <a href=\"https:\/\/www.ninjaone.com\/de\/was-ist-ein-msp\" target=\"_blank\" rel=\"noopener\">Managed Service Provider (MSPs)<\/a> und IT-Experten ist die M\u00f6glichkeit, diese Protokolle schnell und genau zu durchsuchen, ausschlaggebend. Ohne effiziente Tools kann diese Aufgabe m\u00fchsam werden, vor allem, wenn es um eine gro\u00dfe Anzahl von Systemen oder komplexe Umgebungen geht.<\/p>\n<p><a href=\"https:\/\/www.ninjaone.com\/it-hub\/endpoint-management\/what-is-powershell\/\" target=\"_blank\" rel=\"noopener\">PowerShell<\/a>, eine von Microsoft entwickelte leistungsstarke Skriptsprache, bietet solide Funktionen f\u00fcr die Interaktion mit Ereignisprotokollen. Das Skript, das wir heute besprechen, wurde entwickelt, um den Suchprozess zu optimieren und es IT-Experten zu erm\u00f6glichen, relevante Ereignisse in der Ereignisanzeige schnell zu finden.<\/p>\n<h2>Das Skript:<\/h2>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\">#Requires -Version 5.1\r\n\r\n&lt;#\r\n.SYNOPSIS\r\n    Search for specific events in Event Viewer based on the event log they were in, the source of the event, or the specific event IDs used. One of these three options is required for the search.\r\n.DESCRIPTION\r\n    Search for specific events in Event Viewer based on the event log they were in, the source of the event, or the specific event IDs used. One of these three options is required for the search.\r\n.EXAMPLE\r\n    -EventLogName \"Application\"\r\n    \r\n    Matching Events Found!\r\n\r\n    LogName      : Application\r\n    ProviderName : Microsoft-Windows-Security-SPP\r\n    Id           : 16384\r\n    TimeCreated  : 4\/4\/2024 10:00:48 AM\r\n    Message      : Successfully scheduled Software Protection service for re-start at 2024-04-04T21:19:48Z. Reason: Rul...\r\n\r\n    LogName      : Application\r\n    ProviderName : Microsoft-Windows-Security-SPP\r\n    Id           : 16394\r\n    TimeCreated  : 4\/4\/2024 10:00:17 AM\r\n    Message      : Offline downlevel migration succeeded.\r\n\r\n    LogName      : Application\r\n    ProviderName : Microsoft-Windows-Security-SPP\r\n    Id           : 16384\r\n    TimeCreated  : 4\/4\/2024 9:59:59 AM\r\n    Message      : Successfully scheduled Software Protection service for re-start at 2024-04-04T21:19:59Z. Reason: Rul...\r\n\r\nPARAMETER: -EventLogName \"Application\"\r\n    Specify the name of the Event Log from which to retrieve events.\r\n\r\nPARAMETER: -EventLogSource \"Microsoft-Windows-Kernel-General\"\r\n    Determines the source of the events to retrieve.\r\n\r\nPARAMETER: -EventLogMessage \"Alert\"\r\n    Filters events by the text contained in the event's message.\r\n\r\nPARAMETER: -EventIDs \"12, 13, 6008\"\r\n    A comma-separated list of event IDs to include in the search.\r\n\r\nPARAMETER: -excludeEventIDs \"13\"\r\n    A comma-separated list of event IDs to exclude from the search.\r\n\r\nPARAMETER: -StartDate \"12\/24\/2021\"\r\n    Defines the start date and time for the event search. Events logged before this time will not be included in the results.\r\n\r\nPARAMETER: -EndDate \"12\/29\/2021\"\r\n    Sets the end date and time for the event search. Events logged after this time will not be included.\r\n\r\nPARAMETER: -MultilineCustomField \"replaceMeWithAcustomFieldName\"\r\n    Specify the name of a multiline custom field to optionally store the search results in. Leave blank to not set a multiline field.\r\n\r\nPARAMETER: -WysiwygCustomField \"replaceMeWithACustomFieldName\"\r\n    Specify the name of a WYSIWYG custom field to optionally store the search results in. Leave blank to not set a WYSIWYG field.\r\n.NOTES\r\n    Minimum OS Architecture Supported: Windows 10, Windows Server 2016\r\n    Release Notes: Initial Release\r\nBy using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https:\/\/www.ninjaone.com\/terms-of-use.\r\n    Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. \r\n    Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. \r\n    Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. \r\n    Warranty Disclaimer: The script is provided \u201cas is\u201d and \u201cas available\u201d, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. \r\n    Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. \r\n    Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. \r\n    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).\r\n#&gt;\r\n\r\n[CmdletBinding()]\r\nparam (\r\n    [Parameter()]\r\n    [String]$EventLogName,\r\n    [Parameter()]\r\n    [String]$EventLogSource,\r\n    [Parameter()]\r\n    [String]$EventLogMessage,\r\n    [Parameter()]\r\n    [String]$EventIDs,\r\n    [Parameter()]\r\n    [String]$ExcludeEventIDs,\r\n    [Parameter()]\r\n    [datetime]$StartDate,\r\n    [Parameter()]\r\n    [datetime]$EndDate,\r\n    [Parameter()]\r\n    [String]$MultilineCustomField,\r\n    [Parameter()]\r\n    [String]$WysiwygCustomField\r\n)\r\n\r\nbegin {\r\n    # Set parameters using dynamic script variables.\r\n    if ($env:eventLogName -and $env:eventLogName -notlike \"null\") { $EventLogName = $env:eventLogName }\r\n    if ($env:eventLogSource -and $env:eventLogSource -notlike \"null\") { $EventLogSource = $env:eventLogSource }\r\n    if ($env:eventLogMessage -and $env:eventLogMessage -notlike \"null\") { $EventLogMessage = $env:eventLogMessage }\r\n    if ($env:eventIds -and $env:eventIds -notlike \"null\") { $EventIDs = $env:eventIds }\r\n    if ($env:excludeEventIds -and $env:excludeEventIds -notlike \"null\") { $ExcludeEventIDs = $env:excludeEventIds }\r\n    if ($env:eventStart -and $env:eventStart -notlike \"null\") { $StartDate = $env:eventStart }\r\n    if ($env:eventEnd -and $env:eventEnd -notlike \"null\") { $EndDate = $env:eventEnd }\r\n    if ($env:multilineCustomFieldName -and $env:multilineCustomFieldName -notlike \"null\") { $MultilineCustomField = $env:multilineCustomFieldName }\r\n    if ($env:wysiwygCustomFieldName -and $env:wysiwygCustomFieldName -notlike \"null\") { $WysiwygCustomField = $env:wysiwygCustomFieldName }\r\n\r\n    # Check if both StartDate and EndDate are provided and if StartDate is earlier than EndDate\r\n    if (($StartDate -and $EndDate) -and $StartDate -gt $EndDate) {\r\n        Write-Host -Object \"[Error] Start date cannot be earlier than end date!\"\r\n        exit 1\r\n    }\r\n\r\n    # Verify that WysiwygField and MultiLineField are not the same, exiting with an error if they are.\r\n    if ($WysiwygCustomField -and $MultilineCustomField -and ($WysiwygCustomField -eq $MultilineCustomField)) {\r\n        Write-Host -Object \"[Error] Wysiwyg Field and Multiline Field are the same! Custom fields cannot be the same type.\"\r\n        Write-Host -Object \"https:\/\/ninjarmm.zendesk.com\/hc\/en-us\/articles\/18601842971789-Custom-Fields-by-Type-and-Functionality\"\r\n        exit 1\r\n    }\r\n\r\n    # Ensure that at least one of Event ID, Event Log Name, or Event Source is provided for the query\r\n    if (!$EventIDs -and !$EventLogName -and !$EventLogSource) {\r\n        Write-Host -Object \"[Error] You must provide either an Event ID, Event Log Name or Event Source.\"\r\n        exit 1\r\n    }\r\n\r\n    # Trimming trailing spaces.\r\n    if ($EventLogName) {\r\n        $EventLogName = $EventLogName.Trim()\r\n    }\r\n\r\n    # Retrieve and sort all event log names available on the system\r\n    $EventLogNamesOnSystem = Get-WinEvent -ListLog * -ErrorAction SilentlyContinue | Sort-Object LogName\r\n    # Check if the provided EventLogName exists in the system's event logs\r\n    if ($EventLogName -and ($EventLogNamesOnSystem).LogName -notcontains $EventLogName) {\r\n        # If not found, print an error message and a list of valid event log names, then exit the script\r\n        Write-Host -Object \"[Error] Event Log '$EventLogName' doesn't exist! See the list below for valid event log names.\"\r\n        Write-Host -Object \"### Valid Event Log Names ###\"\r\n        $EventLogNamesOnSystem | Select-Object -ExpandProperty LogName | Write-Host\r\n        exit 1 \r\n    }\r\n\r\n    $InvalidEventSourceCharacters = \"[\\\\\/&lt;&gt;&amp;`\"%\\|']\"\r\n    if ($EventLogSource) {\r\n        if ($EventLogSource -match $InvalidEventSourceCharacters) {\r\n            Write-Host -Object \"[Error] Event Log Source '$EventLogSource' contains an invalid character!\"\r\n            exit 1\r\n        }\r\n\r\n        if ($EventLogSource.Length -gt 255) {\r\n            Write-Host -Object \"[Error] Event Log Source '$EventLogSource' is too large to be an event source!\"\r\n            exit 1\r\n        }\r\n\r\n        # Trims the event log source for trailing spaces\r\n        $EventLogSource = $EventLogSource.Trim()\r\n    }\r\n\r\n    # Prepare a list to hold valid event IDs to search for\r\n    $EventIdsToSearch = New-Object System.Collections.Generic.List[int]\r\n    # Process the input event IDs, removing any that are not purely numerical\r\n    if ($EventIDs -and $EventIDs -match \",\") {\r\n        # If multiple event IDs are provided and separated by commas, split them\r\n        $EventIDs -split \",\" | ForEach-Object {\r\n            $EventId = $_.Trim()\r\n            # Validate each event ID to ensure it's numerical\r\n            if ($EventId -match '[a-zA-Z]|\\W') {\r\n                # If not, print an error and skip adding this ID to the list\r\n                Write-Host \"[Error] Event ID '$EventId' is not a valid event id. Removing it from the search.\"\r\n                $ExitCode = 1\r\n                return\r\n            }\r\n            # Check size of event id\r\n            if ([long]$EventId -gt 65535 -or [long]$EventId -lt 0) {\r\n                Write-Host \"[Error] Event ID '$EventId' is not a valid event id. Event ID's must be less than or equal to 65535 and greater than or equal to 0. Removing it from the search.\"\r\n                $ExitCode = 1\r\n                return\r\n            }\r\n             \r\n            # Add the validated event ID to the list\r\n            $EventIdsToSearch.Add($EventId)\r\n        }\r\n    }\r\n    elseif ($EventIDs) {\r\n        $EventId = $EventIDs.Trim()\r\n        # Handle a single event ID input\r\n        if ($EventId -match '[a-zA-Z]|\\W') {\r\n            Write-Host \"[Error] Event ID '$EventId' is not a valid event id. Removing it from the search.\"\r\n            $ExitCode = 1\r\n        }\r\n        elseif ([long]$EventId -gt 65535 -or [long]$EventId -lt 0) {\r\n            Write-Host \"[Error] Event ID '$EventId' is not a valid event id. Event ID's must be less than or equal to 65535 and greater than or equal to 0. Removing it from the search.\"\r\n            $ExitCode = 1\r\n        }\r\n        else {\r\n            $EventIdsToSearch.Add($EventId)\r\n        }\r\n    }\r\n \r\n    # Prepare a list to hold event IDs that should be excluded from the search\r\n    $EventsToExclude = New-Object System.Collections.Generic.List[int]\r\n     \r\n    # Similar process for excluded event IDs as regular event IDs\r\n    if ($ExcludeEventIDs -and $ExcludeEventIDs -match \",\") {\r\n        $ExcludeEventIDs -split \",\" | ForEach-Object {\r\n            $ExcludeEventId = $_.Trim()\r\n            if ($ExcludeEventId -match '[a-zA-Z]|\\W') {\r\n                Write-Host \"[Error] Event ID '$ExcludeEventId' is not a valid event id. Removing it from the exclusions.\"\r\n                $ExitCode = 1\r\n                return\r\n            }\r\n \r\n            if ([long]$ExcludeEventId -gt 65535 -or [long]$ExcludeEventId -lt 0) {\r\n                Write-Host \"[Error] Event ID '$ExcludeEventId' is not a valid event id. Event ID's must be less than or equal to 65535 and greater than or equal to 0. Removing it from the exclusions.\"\r\n                $ExitCode = 1\r\n                return\r\n            }\r\n             \r\n            $EventsToExclude.Add($ExcludeEventId)\r\n        }\r\n    }\r\n    elseif ($ExcludeEventIDs) {\r\n        $ExcludeEventId = $ExcludeEventIDs.Trim()\r\n        if ($ExcludeEventId -match '[a-zA-Z]|\\W') {\r\n            Write-Host \"[Error] Event ID '$ExcludeEventId' is not a valid event id. Removing it from the exclusions.\"\r\n            $ExitCode = 1\r\n        }\r\n        elseif ([long]$ExcludeEventId -gt 65535 -or [long]$ExcludeEventId -lt 0) {\r\n            Write-Host \"[Error] Event ID '$ExcludeEventId' is not a valid event id. Event ID's must be less than or equal to 65535 and greater than or equal to 0. Removing it from the exclusions.\"\r\n            $ExitCode = 1\r\n        }\r\n        else {\r\n            $EventsToExclude.Add($ExcludeEventId)\r\n        }\r\n    }\r\n \r\n    # Check if there are any event IDs to exclude and if the list of event IDs to search for is not empty.\r\n    if ($EventsToExclude.Count -gt 0 -and $EventIdsToSearch.Count -gt 0) {\r\n        $EventsToExclude | ForEach-Object {\r\n            # Check if the current event ID from the exclusion list is also in the list of event IDs to search for.\r\n            if ($EventIdsToSearch -contains $_) {\r\n                Write-Warning \"Event ID $_ has been specified for both inclusion and exclusion. It will be excluded.\"\r\n            }\r\n        }\r\n    }\r\n \r\n    # Check if there's no valid event ID, log name, or log source provided and exit if true\r\n    if ($EventIdsToSearch.Count -eq 0 -and !$EventLogName -and !$EventLogSource) {\r\n        Write-Host \"[Error] No valid Event ID given and no Event Log Name or Event Log Source given.\"\r\n        exit 1\r\n    }\r\n\r\n    # Handy function to set a custom field.\r\n    function Set-NinjaProperty {\r\n        [CmdletBinding()]\r\n        Param(\r\n            [Parameter(Mandatory = $True)]\r\n            [String]$Name,\r\n            [Parameter()]\r\n            [String]$Type,\r\n            [Parameter(Mandatory = $True, ValueFromPipeline = $True)]\r\n            $Value,\r\n            [Parameter()]\r\n            [String]$DocumentName\r\n        )\r\n\r\n        $Characters = $Value | Out-String | Measure-Object -Character | Select-Object -ExpandProperty Characters\r\n        if ($Characters -ge 200000) {\r\n            throw [System.ArgumentOutOfRangeException]::New(\"Character limit exceeded, value with $Characters characters is greater than or equal to 200,000 characters.\")\r\n        }\r\n    \r\n        # If we're requested to set the field value for a Ninja document we'll specify it here.\r\n        $DocumentationParams = @{}\r\n        if ($DocumentName) { $DocumentationParams[\"DocumentName\"] = $DocumentName }\r\n    \r\n        # This is a list of valid fields that can be set. If no type is given, it will be assumed that the input doesn't need to be changed.\r\n        $ValidFields = \"Attachment\", \"Checkbox\", \"Date\", \"Date or Date Time\", \"Decimal\", \"Dropdown\", \"Email\", \"Integer\", \"IP Address\", \"MultiLine\", \"MultiSelect\", \"Phone\", \"Secure\", \"Text\", \"Time\", \"URL\", \"WYSIWYG\"\r\n        if ($Type -and $ValidFields -notcontains $Type) { Write-Warning \"$Type is an invalid type! Please check here for valid types. https:\/\/ninjarmm.zendesk.com\/hc\/en-us\/articles\/16973443979789-Command-Line-Interface-CLI-Supported-Fields-and-Functionality\" }\r\n    \r\n        # The field below requires additional information to be set\r\n        $NeedsOptions = \"Dropdown\"\r\n        if ($DocumentName) {\r\n            if ($NeedsOptions -contains $Type) {\r\n                # We'll redirect the error output to the success stream to make it easier to error out if nothing was found or something else went wrong.\r\n                $NinjaPropertyOptions = Ninja-Property-Docs-Options -AttributeName $Name @DocumentationParams 2&gt;&amp;1\r\n            }\r\n        }\r\n        else {\r\n            if ($NeedsOptions -contains $Type) {\r\n                $NinjaPropertyOptions = Ninja-Property-Options -Name $Name 2&gt;&amp;1\r\n            }\r\n        }\r\n    \r\n        # If an error is received it will have an exception property, the function will exit with that error information.\r\n        if ($NinjaPropertyOptions.Exception) { throw $NinjaPropertyOptions }\r\n    \r\n        # The below type's require values not typically given in order to be set. The below code will convert whatever we're given into a format ninjarmm-cli supports.\r\n        switch ($Type) {\r\n            \"Checkbox\" {\r\n                # While it's highly likely we were given a value like \"True\" or a boolean datatype it's better to be safe than sorry.\r\n                $NinjaValue = [System.Convert]::ToBoolean($Value)\r\n            }\r\n            \"Date or Date Time\" {\r\n                # Ninjarmm-cli expects the GUID of the option to be selected. Therefore, the given value will be matched with a GUID.\r\n                $Date = (Get-Date $Value).ToUniversalTime()\r\n                $TimeSpan = New-TimeSpan (Get-Date \"1970-01-01 00:00:00\") $Date\r\n                $NinjaValue = $TimeSpan.TotalSeconds\r\n            }\r\n            \"Dropdown\" {\r\n                # Ninjarmm-cli is expecting the guid of the option we're trying to select. So we'll match up the value we were given with a guid.\r\n                $Options = $NinjaPropertyOptions -replace '=', ',' | ConvertFrom-Csv -Header \"GUID\", \"Name\"\r\n                $Selection = $Options | Where-Object { $_.Name -eq $Value } | Select-Object -ExpandProperty GUID\r\n    \r\n                if (-not $Selection) {\r\n                    throw [System.ArgumentOutOfRangeException]::New(\"Value is not present in dropdown\")\r\n                }\r\n    \r\n                $NinjaValue = $Selection\r\n            }\r\n            default {\r\n                # All the other types shouldn't require additional work on the input.\r\n                $NinjaValue = $Value\r\n            }\r\n        }\r\n    \r\n        # We'll need to set the field differently depending on if its a field in a Ninja Document or not.\r\n        if ($DocumentName) {\r\n            $CustomField = Ninja-Property-Docs-Set -AttributeName $Name -AttributeValue $NinjaValue @DocumentationParams 2&gt;&amp;1\r\n        }\r\n        else {\r\n            $CustomField = $NinjaValue | Ninja-Property-Set-Piped -Name $Name 2&gt;&amp;1\r\n        }\r\n    \r\n        if ($CustomField.Exception) {\r\n            throw $CustomField\r\n        }\r\n    }\r\n\r\n    function Test-IsElevated {\r\n        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()\r\n        $p = New-Object System.Security.Principal.WindowsPrincipal($id)\r\n        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)\r\n    }\r\n\r\n    if (!$ExitCode) {\r\n        $ExitCode = 0\r\n    }\r\n}\r\nprocess {\r\n    # Check if the script is running with elevated (Administrator) privileges\r\n    if (!(Test-IsElevated)) {\r\n        # If not, display an error message and exit with status code 1\r\n        Write-Host -Object \"[Error] Access Denied. Please run with Administrator privileges.\"\r\n        exit 1\r\n    }\r\n\r\n    # Prepare a list to hold event log names to search for\r\n    $EventLogNamesToSearch = New-Object System.Collections.Generic.List[string]\r\n\r\n    # If no event log name was required we'll search all the event\r\n    if (!$EventLogName) {\r\n        $EventLogNamesOnSystem | Where-Object { $_.RecordCount -gt 0 } | Select-Object -ExpandProperty LogName | ForEach-Object {\r\n            $EventLogNamesToSearch.Add($_)\r\n        }\r\n    }\r\n    else {\r\n        $EventLogNamesToSearch.Add($EventLogName)\r\n    }\r\n\r\n    # Create XML object.\r\n    [xml]$XML = New-Object System.Xml.XmlDocument\r\n\r\n    # Add QueryList element to xml.\r\n    $QueryList = $XML.CreateElement(\"QueryList\")\r\n    $QueryList = $XML.AppendChild($QueryList)\r\n\r\n    # Create query element and nest it under QueryList.\r\n    $Query = $XML.CreateElement(\"Query\")\r\n    $Query.SetAttribute(\"Id\", \"0\")\r\n    $Query = $QueryList.AppendChild($Query)\r\n    \r\n\r\n    # Foreach event log to search we're going to create a select element.\r\n    $EventLogNamesToSearch | ForEach-Object {\r\n        # We'll start each loop by selecting the query element to add to.\r\n        $Query = $XML.SelectSingleNode(\"\/\/Query\")\r\n\r\n        # The select element starts off with the event log to search.\r\n        $Select = $XML.CreateElement(\"Select\")\r\n        $Select.SetAttribute(\"Path\", \"$_\")\r\n        \r\n        # Reset the inner text between runnings\r\n        $XMLInnerText = $Null\r\n\r\n        # The inner text of each element (&lt;Element1&gt;InnerText&lt;\/Element1&gt;) will need to be built differently depending on the parameters.\r\n        if ($EventLogSource) {\r\n            $XMLInnerText = \"*[System[Provider[@Name='$EventLogSource']]]\"\r\n        }\r\n        \r\n        # If we're given a select number of event id's to search we'll filter them here.\r\n        if ($EventIdsToSearch.Count -gt 0) {\r\n            $EventIDSearchText = $Null\r\n            $EventIdsToSearch | ForEach-Object {\r\n                # We may have been given one event id or more than one.\r\n                if ($EventIDSearchText) {\r\n                    $EventIDSearchText = \"$EventIDSearchText or EventID=$_\"\r\n                }\r\n                else {\r\n                    $EventIDSearchText = \"EventID=$_\"\r\n                }\r\n            }\r\n\r\n            # We'll replace the two ending brackets with our given search text\r\n            if ($XMLInnerText) {\r\n                $XMLInnerText = $XMLInnerText -replace ']]$', \" and ($EventIDSearchText)]]\"\r\n            }\r\n            else {\r\n                $XMLInnerText = \"*[System[($EventIDSearchText)]]\"\r\n            }\r\n        }\r\n\r\n        # If we're also asked to filter based on the date the event was created we'll create the filter text here.\r\n        if ($StartDate -or $EndDate) {\r\n            $DateFilter = $Null \r\n            if ($StartDate) {\r\n                $XMLstartDate = Get-Date $StartDate -Format \"yyyy-MM-ddTHH:mm:ss\"\r\n                # PowerShell will convert the &lt; or &gt; symbol for us when we go to save to the xml.\r\n                $DateFilter = \"@SystemTime&gt;='$XMLstartDate'\"\r\n            }\r\n\r\n            # We may or may not have been given a start date.\r\n            if ($EndDate -and $DateFilter) {\r\n                $XMLendDate = Get-Date $EndDate -Format \"yyyy-MM-ddTHH:mm:ss\"\r\n                $DateFilter = \"$DateFilter and @SystemTime&lt;='$XMLendDate'\"\r\n            }\r\n            elseif ($EndDate) {\r\n                $XMLendDate = Get-Date $EndDate -Format \"yyyy-MM-ddTHH:mm:ss\"\r\n                $DateFilter = \"@SystemTime&lt;='$XMLendDate'\"\r\n            }\r\n\r\n            # Replace the last two closing brackets and add our filter text.\r\n            if($XMLInnerText){\r\n                $XMLInnerText = $XMLInnerText -replace ']]$', \" and TimeCreated[$DateFilter]]]\"\r\n            }else{\r\n                $XMLInnerText = \"*[System[TimeCreated[$DateFilter]]]\"\r\n            }\r\n        }\r\n\r\n        # If no filters were given (other than the event log name) we'll need to select everything in that log\r\n        if(!$XMLInnerText){\r\n            $XMLInnerText = \"*\"\r\n        }\r\n\r\n        # Save our filter text to the select statement\r\n        $Select.InnerText = $XMLInnerText\r\n\r\n        # Append our select statement to our xml file\r\n        $Query.AppendChild($Select) | Out-Null\r\n    }\r\n\r\n    # Search for matching events using the XML filter\r\n    $MatchingEvents = Get-WinEvent -FilterXml $XML -ErrorAction SilentlyContinue\r\n\r\n    # Exclude events based on the excluded event IDs if any are specified\r\n    if ($EventsToExclude.Count -gt 0) {\r\n        $MatchingEvents = $MatchingEvents | Where-Object { $EventsToExclude -notcontains $_.ID }\r\n    }\r\n\r\n    # Exclude events that do not match the keywords you specified.\r\n    if ($EventLogMessage) {\r\n        $MatchingEvents = $MatchingEvents | Where-Object { $_.Message -like \"*$EventLogMessage*\" }\r\n    }\r\n\r\n    # If the event log message is larger than 100 characters trim it and add ...\r\n    if ($MatchingEvents) {\r\n        $MatchingEvents = $MatchingEvents | Select-Object LevelDisplayName, LogName, ProviderName, Id, TimeCreated, @{\r\n            Name       = 'Message'\r\n            Expression = {\r\n                $Characters = $_.Message | Measure-Object -Character | Select-Object -ExpandProperty Characters\r\n                if ($Characters -gt 100) {\r\n                    \"$(($_.Message).SubString(0,100))(...)\"\r\n                }\r\n                else {\r\n                    $_.Message\r\n                }\r\n            }\r\n        }\r\n\r\n        # Sort the object by newest event to oldest\r\n        $MatchingEvents = $MatchingEvents | Sort-Object TimeCreated -Descending\r\n    }\r\n\r\n    # Set a Wysiwyg custom field if any matching events are found and it was requested.\r\n    if ($WysiwygCustomField -and $MatchingEvents) {\r\n        try {\r\n            Write-Host \"Attempting to set Custom Field '$WysiwygCustomField'.\"\r\n\r\n            # Prepare the custom field output.\r\n            $CustomFieldValue = New-Object System.Collections.Generic.List[string]\r\n\r\n            # Convert the matching events into an html report.\r\n            $htmlTable = $MatchingEvents | Select-Object -Property LevelDisplayName, LogName, ProviderName, Id, TimeCreated, Message | ConvertTo-Html -Fragment\r\n            \r\n            # Set color coding\r\n            $htmlTable = $htmlTable -replace \"&lt;tr&gt;&lt;td&gt;Verbose&lt;\/td&gt;\", \"&lt;tr class=`\"other`\"&gt;&lt;td&gt;Verbose&lt;\/td&gt;\"\r\n            $htmlTable = $htmlTable -replace \"&lt;tr&gt;&lt;td&gt;Warning&lt;\/td&gt;\", \"&lt;tr class=`\"warning`\"&gt;&lt;td&gt;Warning&lt;\/td&gt;\"\r\n            $htmlTable = $htmlTable -replace \"&lt;tr&gt;&lt;td&gt;Error&lt;\/td&gt;\", \"&lt;tr class=`\"danger`\"&gt;&lt;td&gt;Error&lt;\/td&gt;\"\r\n            $htmlTable = $htmlTable -replace \"&lt;tr&gt;&lt;td&gt;Critical Error&lt;\/td&gt;\", \"&lt;tr class=`\"danger`\"&gt;&lt;td&gt;Critical Error&lt;\/td&gt;\"\r\n\r\n            # Remove Level Display Name\r\n            $LevelDisplayNames = $MatchingEvents | Select-Object -Property LevelDisplayName -Unique\r\n            $LevelDisplayNames | ForEach-Object {\r\n                $htmlTable = $htmlTable -replace \"&lt;td&gt;$([Regex]::Escape($_.LevelDisplayName))&lt;\/td&gt;\"\r\n            }\r\n            $htmlTable = $htmlTable -replace \"&lt;th&gt;LevelDisplayName&lt;\/th&gt;\"\r\n\r\n            # Add the newly created html into the custom field output.\r\n            $CustomFieldValue.Add($htmlTable)\r\n\r\n            # Check that the output complies with the hard character limits.\r\n            $Characters = $CustomFieldValue | Out-String | Measure-Object -Character | Select-Object -ExpandProperty Characters\r\n            if ($Characters -ge 199500) {\r\n                Write-Warning \"200,000 Character Limit has been reached! Trimming output until the character limit is satisified...\"\r\n                \r\n                # If it doesn't comply with the limits we'll need to recreate it with some adjustments.\r\n                $i = 0\r\n                do {\r\n                    # Recreate the custom field output starting with a warning that we truncated the output.\r\n                    $CustomFieldValue = New-Object System.Collections.Generic.List[string]\r\n                    $CustomFieldValue.Add(\"&lt;h1&gt;This info has been truncated to accommodate the 200,000 character limit.&lt;\/h1&gt;\")\r\n\r\n                    # The custom field information is sorted from newest to oldest. We'll remove the oldest first by flipping the array upside down.\r\n                    [array]::Reverse($htmlTable)\r\n                    # If the next entry is a row we'll delete it.\r\n                    if ($htmlTable[$i] -match '&lt;tr&gt;&lt;td&gt;' -or $htmlTable[$i] -match '&lt;tr class=') {\r\n                        $htmlTable[$i] = $null\r\n                    }\r\n                    $i++\r\n                    # We'll flip the array back to right side up.\r\n                    [array]::Reverse($htmlTable)\r\n\r\n                    # Add it back to the output.\r\n                    $CustomFieldValue.Add($htmlTable)\r\n\r\n                    # Check that we now comply with the character limit. If not restart the do loop.\r\n                    $Characters = $CustomFieldValue | Out-String | Measure-Object -Character | Select-Object -ExpandProperty Characters\r\n                }while ($Characters -ge 199500)\r\n            }\r\n\r\n            # Set the custom field.\r\n            Set-NinjaProperty -Name $WysiwygCustomField -Value $CustomFieldValue\r\n            Write-Host \"Successfully set Custom Field '$WysiwygCustomField'!\"\r\n        }\r\n        catch {\r\n            Write-Host \"[Error] $($_.Exception.Message)\"\r\n            $ExitCode = 1\r\n        }\r\n    }\r\n\r\n    # Set a multiline custom field if any matching events are found and it was requested.\r\n    if ($MultilineCustomField -and $MatchingEvents) {\r\n        try {\r\n            Write-Host \"Attempting to set Custom Field '$MultilineCustomField'.\"\r\n            $CustomFieldValue = New-Object System.Collections.Generic.List[string]\r\n\r\n            # We don't want to edit the matching Events array if we have to truncate later so we'll create a duplicate here.\r\n            $CustomFieldList = $MatchingEvents | Select-Object -Property LogName, ProviderName, Id, TimeCreated, Message\r\n\r\n            # Format the matching items into a nice list with the relevant properties.\r\n            $CustomFieldValue.Add(($CustomFieldList | Format-List -Property LogName, ProviderName, Id, TimeCreated, Message | Out-String))\r\n            \r\n            # Check that the output complies with the hard character limits.\r\n            $Characters = $CustomFieldValue | Out-String | Measure-Object -Character | Select-Object -ExpandProperty Characters\r\n            if ($Characters -ge 9500) {\r\n                Write-Warning \"10,000 Character Limit has been reached! Trimming output until the character limit is satisified...\"\r\n                \r\n                # If it doesn't comply with the limits we'll need to recreate it with some adjustments.\r\n                $i = 0\r\n                do {\r\n                    # Recreate the custom field output starting with a warning that we truncated the output.\r\n                    $CustomFieldValue = New-Object System.Collections.Generic.List[string]\r\n                    $CustomFieldValue.Add(\"This info has been truncated to accommodate the 10,000 character limit.\")\r\n                    \r\n                    # The custom field information is sorted from newest to oldest. We'll remove the oldest events first by flipping the array upside down.\r\n                    [array]::Reverse($CustomFieldList)\r\n\r\n                    # Remove the next item which in this case will be the oldest item.\r\n                    $CustomFieldList[$i] = $null\r\n                    $i++\r\n\r\n                    # We'll flip the array back to right side up.\r\n                    [array]::Reverse($CustomFieldList)\r\n\r\n                    # Add it back to the output.\r\n                    $CustomFieldValue.Add(($CustomFieldList | Format-List -Property LogName, ProviderName, Id, TimeCreated, Message | Out-String))\r\n\r\n                    # Check that we now comply with the character limit. If not restart the do loop.\r\n                    $Characters = $CustomFieldValue | Out-String | Measure-Object -Character | Select-Object -ExpandProperty Characters\r\n                }while ($Characters -ge 9500)\r\n            }\r\n\r\n            Set-NinjaProperty -Name $MultilineCustomField -Value $CustomFieldValue\r\n            Write-Host \"Successfully set Custom Field '$MultilineCustomField'!\"\r\n        }\r\n        catch {\r\n            Write-Host \"[Error] $($_.Exception.Message)\"\r\n            $ExitCode = 1\r\n        }\r\n    }\r\n\r\n    # If any matching events were found output them into the activity log.\r\n    if ($MatchingEvents) {\r\n        Write-Host \"Matching Events Found!\"\r\n        $MatchingEvents | Format-List LogName, ProviderName, Id, TimeCreated, Message | Out-String | Write-Host\r\n    }\r\n    else {\r\n        Write-Host \"No matching events found!\"\r\n    }\r\n\r\n    exit $ExitCode\r\n}\r\nend {\r\n    \r\n    \r\n    \r\n}<\/pre>\n<p>&nbsp;<\/p>\n\n<div class=\"blog-cta-new blog-cta-style-1\"><div class=\"cta-left\"><h2><\/h2><p><\/p><\/div><div class=\"cta-right\"><a class=\"button\" href=\"\"><\/a><\/div><\/div>\n<h2>Das PowerShell-Skript verstehen<\/h2>\n<p>Dieses PowerShell-Skript ist ein vielseitiges Tool, mit dem Benutzer:innen auf der Grundlage verschiedener Kriterien nach bestimmten Ereignissen in der Ereignisanzeige suchen k\u00f6nnen. Das Skript kann Ereignisse nach Protokollnamen, Quelle, Ereignis-ID, Nachrichteninhalt und Datumsbereich filtern. Au\u00dferdem bietet es Optionen, um bestimmte Ereignis-IDs von der Suche auszuschlie\u00dfen und die Ergebnisse in benutzerdefinierten Feldern zu speichern.<\/p>\n<p>Hier finden Sie eine detaillierte Aufschl\u00fcsselung der Funktionsweise des Skripts:<\/p>\n<h3>1. Parameter und Umgebungsvariablen:<\/h3>\n<ul>\n<li>Das Skript beginnt mit dem Festlegen von Parametern, mit denen die Benutzer:innen ihre Suchkriterien definieren k\u00f6nnen, z. B. EventLogName, EventLogSource, EventIDs, StartDate und EndDate. Es unterst\u00fctzt auch Umgebungsvariablen f\u00fcr diese Parameter und erm\u00f6glicht so die Integration in andere Automatisierungsabl\u00e4ufe.<\/li>\n<\/ul>\n<h3>2. Validierung und Fehlerbehandlung:<\/h3>\n<ul>\n<li>Das Skript enth\u00e4lt mehrere Ebenen der Validierung, um sicherzustellen, dass die Eingabeparameter korrekt sind. So wird beispielsweise gepr\u00fcft, ob das angegebene Startdatum vor dem Enddatum liegt, und es wird sichergestellt, dass die Ereignis-IDs numerisch sind und innerhalb des zul\u00e4ssigen Bereichs liegen.<\/li>\n<li>Wenn die Parameter WysiwygCustomField und MultilineCustomField auf denselben Wert gesetzt sind, gibt das Skript einen Fehler aus, um widerspr\u00fcchliche Konfigurationen zu verhindern.<\/li>\n<\/ul>\n<h3>3. Logik der Ereignisprotokollsuche:<\/h3>\n<ul>\n<li>Das Skript erstellt eine XML-Abfrage, um Ereignisse anhand der angegebenen Kriterien zu filtern. Diese Abfrage wird dann mit dem cmdlet &#8222;Get-WinEvent&#8220; verwendet, um passende Ereignisse aus den angegebenen Protokollen abzurufen.<\/li>\n<li>Das Skript erm\u00f6glicht den Ausschluss bestimmter Ereignis-IDs und kann Ereignisse nach dem Inhalt der Nachricht filtern, wodurch es hochgradig anpassbar ist.<\/li>\n<\/ul>\n<h3>4. Benutzerdefinierte Feldeinstellung:<\/h3>\n<ul>\n<li>Wenn passende Ereignisse gefunden werden, kann das Skript die Ergebnisse in benutzerdefinierten Feldern speichern, entweder als mehrzeiliges Textfeld oder als HTML-formatierter Bericht. Diese Funktion ist besonders n\u00fctzlich f\u00fcr MSPs, die Ergebnisse dokumentieren oder die Berichterstattung automatisieren m\u00fcssen.<\/li>\n<\/ul>\n<h3>5. Ausgabe und Sortierung:<\/h3>\n<ul>\n<li>Das Skript gibt die Ergebnisse in einem lesbaren Format aus, sortiert sie nach dem Zeitpunkt der Erstellung der Ereignisse, vom neuesten bis zum \u00e4ltesten. Au\u00dferdem werden lange Nachrichten gek\u00fcrzt, um die Ausgabe nicht zu \u00fcberladen.<\/li>\n<\/ul>\n<h2>Praktische Anwendungen des Skripts<\/h2>\n<p>Stellen Sie sich ein Szenario vor, in dem ein IT-Experte die Aufgabe hat, wiederkehrende Fehler auf mehreren Servern in einer Unternehmensumgebung zu identifizieren. Das manuelle Durchsuchen der Ereignisprotokolle auf jedem Server w\u00e4re zeitaufw\u00e4ndig und fehleranf\u00e4llig.<\/p>\n<p>Mithilfe dieses PowerShell-Skripts kann der IT-Mitarbeiter den Suchprozess automatisieren, Protokolle auf der Grundlage bestimmter Fehlerereignis-IDs filtern und die Ergebnisse auf einen bestimmten Zeitraum eingrenzen. Dieser Ansatz spart nicht nur Zeit, sondern verbessert auch die Genauigkeit, sodass das IT-Team Probleme schnell diagnostizieren und beheben kann.<\/p>\n<p>Ein weiterer Anwendungsfall k\u00f6nnte die \u00dcberpr\u00fcfung der Compliance sein. Ein MSP muss m\u00f6glicherweise \u00fcberpr\u00fcfen, ob bestimmte Sicherheitsereignisse, wie z. B. erfolgreiche oder fehlgeschlagene Login-Versuche, in den von ihm verwalteten Systemen wie erwartet auftreten. Mit diesem Skript k\u00f6nnen diese Ereignisse extrahiert und Berichte erstellt werden, die die Compliance im Bereich Sicherheit belegen.<\/p>\n<h2>Vergleich von Ans\u00e4tzen f\u00fcr die Suche im Ereignisprotokoll<\/h2>\n<p>Es gibt zwar mehrere Methoden zum Durchsuchen von Ereignisprotokollen, einschlie\u00dflich der integrierten Ereignisanzeige-GUI oder anderer Tools von Drittanbietern, aber dieses PowerShell-Skript bietet deutliche Vorteile. Im Gegensatz zur manuellen Suche \u00fcber die grafische Benutzeroberfl\u00e4che kann dieses Skript automatisiert und in gr\u00f6\u00dfere Arbeitsabl\u00e4ufe integriert werden. Dar\u00fcber hinaus bietet PowerShell im Vergleich zu anderen Tools zahlreiche Anpassungsm\u00f6glichkeiten, sodass IT-Experten die Suchkriterien an ihre spezifischen Anforderungen anpassen k\u00f6nnen.<\/p>\n<h2>H\u00e4ufig gestellte Fragen<\/h2>\n<h3>F: Kann dieses Skript auf Systemen mit \u00e4lteren Windows-Versionen verwendet werden?<\/h3>\n<p>A: Das Skript erfordert Windows PowerShell 5.1 und wird unter Windows 10 und Windows Server 2016 oder h\u00f6her unterst\u00fctzt.<\/p>\n<h3>F: Was passiert, wenn die Zeichengrenze beim Einrichten eines benutzerdefinierten Feldes \u00fcberschritten wird?<\/h3>\n<p>A: Das Skript enth\u00e4lt eine Logik, um die Ausgabe zu k\u00fcrzen, damit sie in die Zeichenbegrenzung passt. So wird sichergestellt, dass das Skript nicht an zu gro\u00dfen Datens\u00e4tzen scheitert.<\/p>\n<h3>F: Ist es m\u00f6glich, mit diesem Skript alle Ereignisprotokolle auf einem System zu durchsuchen?<\/h3>\n<p>A: Ja, wenn kein bestimmter Ereignisprotokollname angegeben wird, durchsucht das Skript alle verf\u00fcgbaren Ereignisprotokolle auf dem System.<\/p>\n<h2>Auswirkungen auf die IT-Sicherheit<\/h2>\n<p>Die Verwendung von PowerShell f\u00fcr effiziente Ereignisprotokollsuchen hat erhebliche Auswirkungen auf die IT-Sicherheit. Indem verd\u00e4chtige oder anomale Ereignisse schnell erkannt werden, k\u00f6nnen IT-Experten effektiver auf potenzielle Sicherheitsvorf\u00e4lle reagieren. Die von diesem Skript gebotene Automatisierung verringert das Risiko menschlicher Fehler und stellt sicher, dass kritische Ereignisse nicht \u00fcbersehen werden.<\/p>\n<h2>Best Practices f\u00fcr die Verwendung des Skripts<\/h2>\n<ul>\n<li><strong>Testen Sie das Skript immer in einer kontrollierten Umgebung, bevor Sie es in der Produktion bereitstellen.<\/strong><\/li>\n<li><strong>Verwenden Sie Umgebungsvariablen, um das Skript in gr\u00f6\u00dfere Automatisierungsabl\u00e4ufe zu integrieren.<\/strong><\/li>\n<li><strong>Aktualisieren Sie das Skript regelm\u00e4\u00dfig, um neue Funktionen einzubauen oder potenzielle Sicherheitsl\u00fccken zu schlie\u00dfen.<\/strong><\/li>\n<\/ul>\n<h2>Abschlie\u00dfende \u00dcberlegungen<\/h2>\n<p>Eine effiziente Verwaltung von Ereignisprotokollen ist f\u00fcr die Aufrechterhaltung des Systemzustands, die Gew\u00e4hrleistung der Sicherheit und die Compliance unerl\u00e4sslich. Dieses PowerShell-Skript bietet IT-Experten ein leistungsstarkes Tool zum Durchsuchen und Analysieren von Ereignisprotokollen, mit dem sie ihre Aufgaben effektiver erledigen k\u00f6nnen.<\/p>\n<p>F\u00fcr MSPs und IT-Teams, die mehrere Systeme verwalten, bietet <a href=\"https:\/\/www.ninjaone.com\/de\/\" target=\"_blank\" rel=\"noopener\">NinjaOne<\/a> eine komplette Suite von Tools, die das Monitoring und Management der IT-Infrastruktur weiter verst\u00e4rken k\u00f6nnen. Wenn Sie dieses Skript in Ihre Arbeitsabl\u00e4ufe integrieren, k\u00f6nnen Sie die Suche in den Ereignisprotokollen optimieren und Ihre IT-Abl\u00e4ufe insgesamt verbessern.<\/p>\n","protected":false},"author":35,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"open","ping_status":"open","template":"","meta":{"_acf_changed":false,"_relevanssi_hide_post":"","_relevanssi_hide_content":"","_relevanssi_pin_for_all":"","_relevanssi_pin_keywords":"","_relevanssi_unpin_keywords":"","_relevanssi_related_keywords":"","_relevanssi_related_include_ids":"","_relevanssi_related_exclude_ids":"","_relevanssi_related_no_append":"","_relevanssi_related_not_related":"","_relevanssi_related_posts":"","_relevanssi_noindex_reason":"","_lmt_disableupdate":"no","_lmt_disable":""},"operating_system":[4212],"use_cases":[4307],"class_list":["post-353614","script_hub","type-script_hub","status-publish","hentry","script_hub_category-windows","use_cases-allgemeine-konfiguration"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.ninjaone.com\/de\/wp-json\/wp\/v2\/script_hub\/353614","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.ninjaone.com\/de\/wp-json\/wp\/v2\/script_hub"}],"about":[{"href":"https:\/\/www.ninjaone.com\/de\/wp-json\/wp\/v2\/types\/script_hub"}],"author":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/de\/wp-json\/wp\/v2\/users\/35"}],"replies":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/de\/wp-json\/wp\/v2\/comments?post=353614"}],"wp:attachment":[{"href":"https:\/\/www.ninjaone.com\/de\/wp-json\/wp\/v2\/media?parent=353614"}],"wp:term":[{"taxonomy":"script_hub_category","embeddable":true,"href":"https:\/\/www.ninjaone.com\/de\/wp-json\/wp\/v2\/operating_system?post=353614"},{"taxonomy":"use_cases","embeddable":true,"href":"https:\/\/www.ninjaone.com\/de\/wp-json\/wp\/v2\/use_cases?post=353614"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}