{"id":353796,"date":"2024-09-24T07:49:00","date_gmt":"2024-09-24T07:49:00","guid":{"rendered":"https:\/\/www.ninjaone.com\/script-hub\/busqueda-en-registros-de-eventos\/"},"modified":"2024-10-13T19:02:19","modified_gmt":"2024-10-13T19:02:19","slug":"busqueda-en-registros-de-eventos","status":"publish","type":"script_hub","link":"https:\/\/www.ninjaone.com\/es\/script-hub\/busqueda-en-registros-de-eventos\/","title":{"rendered":"Gu\u00eda completa sobre el uso de PowerShell para realizar una b\u00fasqueda en registros de eventos de forma eficaz"},"content":{"rendered":"<p>En el panorama en constante evoluci\u00f3n de las TI, la supervisi\u00f3n y el an\u00e1lisis de los registros de eventos son cruciales para mantener el buen estado del sistema, diagnosticar problemas y garantizar el cumplimiento de las normas de seguridad.<\/p>\n<p>Los registros de eventos son una rica fuente de informaci\u00f3n sobre el estado y el comportamiento de los sistemas, y ser capaces de buscar y filtrar eficientemente estos registros puede mejorar significativamente la capacidad de un profesional de TI para gestionar su infraestructura.<\/p>\n<p>Este art\u00edculo profundiza en un script de PowerShell que simplifica el proceso de <strong>b\u00fasqueda en registros de eventos<\/strong>, facilitando la localizaci\u00f3n de eventos espec\u00edficos en funci\u00f3n de criterios como el nombre del registro de eventos, el origen, el ID del evento, etc.<\/p>\n<h2>La importancia de la gesti\u00f3n de registros de eventos en TI<\/h2>\n<p>Los registros de eventos son registros de sucesos del sistema, seguridad y aplicaciones en un ordenador. Estos registros son indispensables para solucionar problemas, auditar incidentes de seguridad y garantizar el cumplimiento de las normas reglamentarias.<\/p>\n<p>Para <a href=\"https:\/\/www.ninjaone.com\/es\/que-es-un-msp\" target=\"_blank\" rel=\"noopener\">los proveedores de servicios gestionados (MSP)<\/a> y los profesionales de TI, la capacidad de realizar b\u00fasquedas r\u00e1pidas y precisas en estos registros es vital. Sin herramientas eficaces, esta tarea puede resultar engorrosa, sobre todo cuando se trata de un gran n\u00famero de sistemas o entornos complejos.<\/p>\n<p><a href=\"https:\/\/www.ninjaone.com\/it-hub\/endpoint-management\/what-is-powershell\/\" target=\"_blank\" rel=\"noopener\">PowerShell<\/a>, un potente lenguaje de scripting desarrollado por Microsoft, ofrece s\u00f3lidas capacidades para interactuar con los registros de eventos. El script del que hablaremos hoy est\u00e1 dise\u00f1ado para agilizar el proceso de b\u00fasqueda eb registros de eventos, permitiendo a los profesionales de TI localizar r\u00e1pidamente los m\u00e1s relevantes dentro del Visor de eventos.<\/p>\n<h2>El script para realizar una b\u00fasqueda en registros de eventos<\/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=\"in-context-cta\"><\/div>\n<h2>Comprender el script PowerShell<\/h2>\n<p>Este script PowerShell es una herramienta vers\u00e1til que permite a los usuarios buscar eventos espec\u00edficos en el Visor de eventos bas\u00e1ndose en varios criterios. El script puede filtrar los eventos por nombre de registro, fuente, ID de evento, contenido del mensaje y rango de fechas. Adem\u00e1s, ofrece opciones para excluir determinados ID de eventos de la b\u00fasqueda y almacenar los resultados en campos personalizados.<\/p>\n<p>Aqu\u00ed tienes un desglose detallado de c\u00f3mo funciona el script para realizar una b\u00fasqueda en registros de eventos:<\/p>\n<h3>1. Par\u00e1metros y variables de entorno<\/h3>\n<ul>\n<li>El script comienza estableciendo par\u00e1metros que permiten a los usuarios definir sus criterios de b\u00fasqueda, como EventLogName, EventLogSource, EventIDs, StartDate y EndDate. Tambi\u00e9n admite variables de entorno para estos par\u00e1metros, lo que permite la integraci\u00f3n con otros flujos de trabajo de automatizaci\u00f3n.<\/li>\n<\/ul>\n<h3>2. Validaci\u00f3n y tratamiento de errores<\/h3>\n<ul>\n<li>El script para realizar una b\u00fasqueda en registros de eventos incluye m\u00faltiples capas de validaci\u00f3n para garantizar que los par\u00e1metros de entrada son correctos. Por ejemplo, comprueba si la fecha de inicio proporcionada es anterior a la fecha de finalizaci\u00f3n y valida que los ID de los eventos sean num\u00e9ricos y est\u00e9n dentro del intervalo aceptable.<\/li>\n<li>Si los par\u00e1metros WysiwygCustomField y MultilineCustomField tienen el mismo valor, el script lanza un error, evitando configuraciones conflictivas.<\/li>\n<\/ul>\n<h3>3. L\u00f3gica de b\u00fasqueda en el registro de eventos<\/h3>\n<ul>\n<li>El script crea una consulta XML para filtrar los eventos en funci\u00f3n de los criterios proporcionados. A continuaci\u00f3n, esta consulta se utiliza con el cmdlet Get-WinEvent para recuperar los eventos coincidentes de los registros especificados.<\/li>\n<li>El script permite la exclusi\u00f3n de determinados ID de eventos y puede filtrar eventos por el contenido del mensaje, lo que lo hace altamente personalizable.<\/li>\n<\/ul>\n<h3>4. Configuraci\u00f3n de campo personalizada<\/h3>\n<ul>\n<li>Si se encuentran eventos coincidentes, el script para realizar una b\u00fasqueda en registros de eventos puede almacenar los resultados en campos personalizados, ya sea como un campo de texto multil\u00ednea o como un informe con formato HTML. Esta funci\u00f3n es especialmente \u00fatil para los MSP que necesitan documentar hallazgos o automatizar informes.<\/li>\n<\/ul>\n<h3>5. Salida y clasificaci\u00f3n<\/h3>\n<ul>\n<li>El script muestra los resultados en un formato legible, ordenados por la hora de creaci\u00f3n de los eventos, de m\u00e1s reciente a m\u00e1s antiguo. Tambi\u00e9n recorta los mensajes largos para no saturar la salida.<\/li>\n<\/ul>\n<h2>Aplicaciones pr\u00e1cticas del script<\/h2>\n<p>Consideremos un escenario en el que un profesional de TI tiene la tarea de identificar errores recurrentes en varios servidores de un entorno corporativo. Examinar manualmente los registros de eventos de cada servidor llevar\u00eda mucho tiempo y dar\u00eda lugar a errores.<\/p>\n<p>Aprovechando este script de PowerShell, el profesional puede automatizar el proceso de b\u00fasqueda en registros de eventos, filtrando los registros en funci\u00f3n de ID de eventos de error espec\u00edficos y limitando los resultados a un marco temporal concreto. Este enfoque no s\u00f3lo ahorra tiempo, sino que tambi\u00e9n mejora la precisi\u00f3n, lo que permite al equipo inform\u00e1tico diagnosticar y resolver r\u00e1pidamente los problemas.<\/p>\n<p>Otro caso de uso podr\u00eda ser la auditor\u00eda de cumplimiento. Es posible que un MSP necesite verificar que determinados eventos de seguridad, como los intentos de inicio de sesi\u00f3n exitosos o fallidos, se producen seg\u00fan lo esperado en todos sus sistemas gestionados. Este script puede utilizarse para extraer estos eventos y generar informes que demuestren el cumplimiento de las pol\u00edticas de seguridad.<\/p>\n<h2>Comparaci\u00f3n de m\u00e9todos de b\u00fasqueda en el registros de eventos<\/h2>\n<p>Aunque existen varios m\u00e9todos para buscar en los registros de eventos, como la interfaz gr\u00e1fica de usuario integrada del Visor de eventos u otras herramientas de terceros, este script de PowerShell ofrece claras ventajas. A diferencia de las b\u00fasquedas manuales a trav\u00e9s de la GUI, este script puede automatizarse e integrarse en flujos de trabajo m\u00e1s amplios. Adem\u00e1s, en comparaci\u00f3n con otras herramientas, PowerShell ofrece un alto grado de personalizaci\u00f3n, lo que permite a los profesionales de TI adaptar los criterios de b\u00fasqueda a sus necesidades espec\u00edficas.<\/p>\n<h2>Preguntas frecuentes<\/h2>\n<h3>P: \u00bfSe puede utilizar este script para realizar una b\u00fasqueda en registros de eventos en sistemas con versiones anteriores de Windows?<\/h3>\n<p>R: El script requiere Windows PowerShell 5.1 y es compatible con Windows 10 y Windows Server 2016 o versiones posteriores.<\/p>\n<h3>P: \u00bfQu\u00e9 ocurre si se supera el l\u00edmite de caracteres al configurar un campo personalizado?<\/h3>\n<p>R: El script para realizar una b\u00fasqueda en registros de eventos incluye una l\u00f3gica para truncar la salida y ajustarla al l\u00edmite de caracteres, lo que garantiza que el script no falle debido a conjuntos de datos demasiado grandes.<\/p>\n<h3>P: \u00bfEs posible buscar en todos los registros de eventos de un sistema utilizando este script?<\/h3>\n<p>R: S\u00ed, si no se proporciona un nombre de registro de eventos espec\u00edfico, el script buscar\u00e1 en todos los registros de eventos disponibles en el sistema.<\/p>\n<h2>Implicaciones para la seguridad inform\u00e1tica<\/h2>\n<p>La capacidad de realizar b\u00fasquedas eficientes en los registros de eventos tiene importantes implicaciones para la seguridad inform\u00e1tica. Al identificar r\u00e1pidamente los eventos sospechosos o an\u00f3malos, los profesionales de TI pueden responder a posibles incidentes de seguridad con mayor eficacia. La automatizaci\u00f3n que proporciona este script para realizar una b\u00fasqueda en registros reduce el riesgo de error humano y garantiza que no se pasen por alto los eventos cr\u00edticos.<\/p>\n<h2>Buenas pr\u00e1cticas para utilizar el script<\/h2>\n<ul>\n<li><strong>Prueba siempre el script en un entorno controlado antes de desplegarlo en producci\u00f3n.<\/strong><\/li>\n<li><strong>Utiliza variables de entorno para integrar el script en flujos de trabajo de automatizaci\u00f3n m\u00e1s amplios.<\/strong><\/li>\n<li><strong>Actualiza peri\u00f3dicamente el script para incorporar nuevas funciones o solucionar posibles vulnerabilidades de seguridad.<\/strong><\/li>\n<\/ul>\n<h2>Reflexiones finales<\/h2>\n<p>La gesti\u00f3n eficaz de los registros de eventos es esencial para mantener el buen estado del sistema, garantizar la seguridad y lograr el cumplimiento de las normativas. Este script de PowerShell para realizar una b\u00fasqueda en registros de eventos proporciona a los profesionales de TI una potente herramienta para buscar y analizar registros de eventos, lo que les permite realizar sus tareas con mayor eficacia.<\/p>\n<p>Para los MSP y los equipos de TI que gestionan m\u00faltiples sistemas, <a href=\"https:\/\/www.ninjaone.com\/es\/\" target=\"_blank\" rel=\"noopener\">NinjaOne<\/a> ofrece un completo conjunto de herramientas que pueden mejorar a\u00fan m\u00e1s su capacidad para supervisar y gestionar la infraestructura de TI. Si integras este script en tus flujos de trabajo, puedes agilizar tus b\u00fasquedas en el registro de eventos y mejorar de forma general tus operaciones de TI.<\/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":"","_lmt_disable":""},"operating_system":[4212],"use_cases":[4259],"class_list":["post-353796","script_hub","type-script_hub","status-publish","hentry","script_hub_category-windows","use_cases-configuracion-general"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/script_hub\/353796","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/script_hub"}],"about":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/types\/script_hub"}],"author":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/users\/35"}],"replies":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/comments?post=353796"}],"wp:attachment":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/media?parent=353796"}],"wp:term":[{"taxonomy":"script_hub_category","embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/operating_system?post=353796"},{"taxonomy":"use_cases","embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/use_cases?post=353796"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}