{"id":208623,"date":"2024-01-31T14:44:58","date_gmt":"2024-01-31T14:44:58","guid":{"rendered":"https:\/\/www.ninjaone.com\/script-hub\/detectar-analizar-bsod-powershell\/"},"modified":"2024-03-04T18:39:08","modified_gmt":"2024-03-04T18:39:08","slug":"detectar-analizar-bsod-powershell","status":"publish","type":"script_hub","link":"https:\/\/www.ninjaone.com\/es\/script-hub\/detectar-analizar-bsod-powershell\/","title":{"rendered":"C\u00f3mo detectar y analizar las BSOD con PowerShell"},"content":{"rendered":"<p>La <a href=\"https:\/\/www.ninjaone.com\/es\/blog\/pantalla-azul-de-la-muerte-bsod\/\">pantalla azul de la muerte (BSOD)<\/a> es un t\u00e9rmino del mundo de la inform\u00e1tica que a menudo produce escalofr\u00edos en los usuarios. Es una pantalla de error de parada que aparece en un sistema inform\u00e1tico Windows tras un error fatal del sistema. A menudo causadas por problemas de hardware o controladores, las BSOD tambi\u00e9n pueden ser desencadenadas por errores de software, provocando una interrupci\u00f3n brusca del funcionamiento del sistema. Comprender y diagnosticar estos errores es primordial en el \u00e1mbito de las TI y, por eso, en este post profundizaremos en un script de PowerShell dise\u00f1ado para detectar y registrar estos cierres inesperados.<\/p>\n<h2>Antecedentes<\/h2>\n<p>El script utiliza la <a href=\"https:\/\/www.nirsoft.net\/utils\/blue_screen_view.html\" target=\"_blank\" rel=\"noopener\">herramienta BlueScreenView de Nirsoft<\/a>, una utilidad dise\u00f1ada espec\u00edficamente para analizar archivos minidump generados durante una BSOD. Para los profesionales de TI y los proveedores de servicios gestionados (MSP), la automatizaci\u00f3n del proceso de detecci\u00f3n y an\u00e1lisis de estos archivos minidump tiene un valor incalculable, ya que ofrece un enfoque sistem\u00e1tico para la soluci\u00f3n de problemas.<\/p>\n<h2>El script para detectar y analizar pantallas azules de la muerte (BSOD)<\/h2>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\">#Requires -Version 5.1\r\n\r\n&lt;#\r\n.SYNOPSIS\r\n    Conditional script for detecting BSOD's. Uses BlueScreenView from Nirsoft.\r\n.DESCRIPTION\r\n    Conditional script for detecting BSOD's. Uses BlueScreenView from Nirsoft.\r\n    Will always show the number of Unexpected shutdowns if system is setup to log those events.\r\n        This doesn't always mean that there was a BSOD as this includes things like holding the power button or pressing the rest button.\r\n    When a mini dump is detected in C:WindowsMinidump then this will output the results and exit with an exit code of 1.\r\n    When none have been found then this will exit with an exit code of 0.\r\n    When it couldn't download or extract BlueScreenView then this will exit with an exit code of 2.\r\n.OUTPUTS\r\n    None\r\n.NOTES\r\n    This should be the default, but in case this was modified instructions below.\r\n    Minimal Setup:\r\n        Open System Properties.\r\n        Click on Settings under Startup and Recovery.\r\n        Make sure that \"Write an event to the system log\" is checked.\r\n        Under System failure change to \"Write debugging information\" to Automatic memory dump.\r\n    Minimum OS Architecture Supported: Windows 10, Windows Server 2016\r\n    Release Notes:\r\n    Initial Release\r\n    (c) 2023 NinjaOne\r\n    By 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\r\nprocess {\r\n    if (-not (Test-IsElevated)) {\r\n        Write-Error -Message \"Access Denied. Please run with Administrator privileges.\"\r\n        exit 1\r\n    }\r\n\r\n    # Get unexpected shutdown events from System log\r\n    $UnexpectedShutdownEvents = Get-WinEvent -FilterHashtable @{LogName = 'System'; ID = 6008 }\r\n    if ($UnexpectedShutdownEvents) {\r\n        Write-Host \"Unexpected shutdowns found: $($UnexpectedShutdownEvents.Count)\"\r\n        Write-Host \"\"\r\n    }\r\n\r\n    # Check if any minidumps exist and exit if none are found\r\n    if (-not $(Get-ChildItem -Path \"C:WindowsMinidump\" -ErrorAction SilentlyContinue)) {\r\n        Write-Host \"No mini dumps found.\"\r\n        exit 0\r\n    }\r\n    \r\n    # Download Blue Screen View, run, and export results to a csv file\r\n    try {\r\n        Invoke-WebRequest -Uri $BlueScreenViewUrl -OutFile $ZipPath -ErrorAction Stop\r\n        Expand-Archive -Path $ZipPath -DestinationPath $ENV:Temp -Force -ErrorAction Stop\r\n        Start-Process -FilePath $ExePath -ArgumentList \"\/scomma \"\"$CsvPath\"\"\" -Wait -ErrorAction Stop\r\n    }\r\n    catch {\r\n        Write-Host \"Blue Screen View Command has Failed: $($_.Exception.Message)\"\r\n        # Clean Up\r\n        Remove-DownloadedFiles -Path $CsvPath, $ZipPath, $ExePath, \"$($ENV:Temp)BlueScreenView.chm\", \"$($ENV:Temp)readme.txt\"\r\n        exit 2\r\n    }\r\n\r\n    # Convert the CSV to an array of objects\r\n    $MiniDumps = Get-Content -Path $CsvPath |\r\n        ConvertFrom-Csv -Delimiter ',' -Header $Header |\r\n        Select-Object -Property @{\r\n            'n' = \"Timestamp\";\r\n            'e' = { [DateTime]::Parse($_.timestamp, [System.Globalization.CultureInfo]::CurrentCulture) }\r\n        }, Dumpfile, Reason, Errorcode, CausedByDriver\r\n\r\n    # Clean Up\r\n    Remove-DownloadedFiles -Path $CsvPath, $ZipPath, $ExePath, \"$($ENV:Temp)BlueScreenView.chm\", \"$($ENV:Temp)readme.txt\"\r\n\r\n    # Output the results\r\n    $MiniDumps | Out-String | Write-Host\r\n\r\n    if ($MiniDumps) {\r\n        exit 1\r\n    }\r\n    exit 0\r\n}\r\nbegin {\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    function Remove-DownloadedFiles {\r\n        param([string[]]$Path)\r\n        process { Remove-Item -Path $Path -Force -ErrorAction SilentlyContinue }\r\n    }\r\n\r\n    # CSV Headers\r\n    $Header = @(\r\n        \"Dumpfile\"\r\n        \"Timestamp\"\r\n        \"Reason\"\r\n        \"Errorcode\"\r\n        \"Parameter1\"\r\n        \"Parameter2\"\r\n        \"Parameter3\"\r\n        \"Parameter4\"\r\n        \"CausedByDriver\"\r\n    )\r\n\r\n    # Build path variables\r\n    $CsvFileName = \"bluescreenview-export.csv\"\r\n    $BlueScreenViewZip = \"bluescreenview.zip\"\r\n    $BlueScreenViewExe = \"BlueScreenView.exe\"\r\n    $BlueScreenViewUrl = \"https:\/\/www.nirsoft.net\/utils\/$BlueScreenViewZip\"\r\n    $ZipPath = Join-Path -Path $ENV:Temp -ChildPath $BlueScreenViewZip\r\n    $ExePath = Join-Path -Path $ENV:Temp -ChildPath $BlueScreenViewExe\r\n    $CsvPath = Join-Path -Path $ENV:Temp -ChildPath $CsvFileName\r\n}\r\nend {}<\/pre>\n<p>&nbsp;<\/p>\n\n\n<h2><strong>An\u00e1lisis detallado<\/strong><\/h2>\n<ol>\n<li><strong>Requisitos previos:<\/strong> el script requiere PowerShell versi\u00f3n 5.1 y est\u00e1 dise\u00f1ado para Windows 10 y Windows Server 2016.<\/li>\n<li><strong>Inicializaci\u00f3n:<\/strong> empieza por asegurarse de que tiene privilegios de administrador, esenciales para acceder a los registros del sistema y a los archivos minidump.<\/li>\n<li><strong>Cierres inesperados:<\/strong> a continuaci\u00f3n, el script comprueba si se han producido cierres inesperados en el registro del sistema.<\/li>\n<li><strong>Control de minidumps:<\/strong> busca archivos minidump en el directorio designado.<\/li>\n<li><strong>Integraci\u00f3n de BlueScreenView:<\/strong> si se detectan archivos minidump, el script descarga y ejecuta BlueScreenView, exportando los resultados a un archivo CSV.<\/li>\n<li><strong>An\u00e1lisis de datos:<\/strong> los datos CSV se convierten en una matriz de objetos que el usuario puede visualizar.<\/li>\n<li><strong>Limpieza:<\/strong> tras el an\u00e1lisis, se eliminan todos los archivos descargados o extra\u00eddos.<\/li>\n<\/ol>\n<h2>Posibles casos de uso<\/h2>\n<p>Pensemos en un profesional de TI, Alex, que ha sido alertado de BSOD recurrentes en el departamento de dise\u00f1o de una empresa. En lugar de examinar manualmente cada sistema, Alex despliega este script. En unos instantes, identifica un controlador espec\u00edfico que causa las BSOD, lo que permite una soluci\u00f3n espec\u00edfica. Este script se convierte as\u00ed en una poderosa herramienta para la resoluci\u00f3n de problemas.<\/p>\n<h2>Comparaciones<\/h2>\n<p>Aunque el Visor de eventos de Windows ofrece informaci\u00f3n, carece del an\u00e1lisis detallado de minidumps que proporciona BlueScreenView. Este script cubre eficazmente ese vac\u00edo, ofreciendo un enfoque m\u00e1s completo que los m\u00e9todos manuales.<\/p>\n<h2>Preguntas frecuentes<\/h2>\n<ul>\n<li><strong>P:<\/strong> \u00bfPuede ejecutarse este script en versiones anteriores de Windows?<br \/>\nR: Est\u00e1 optimizado para Windows 10 y Windows Server 2016. Es posible que las versiones anteriores no admitan todas las funciones.<\/li>\n<li><strong>P:<\/strong> \u00bfQu\u00e9 ocurre si BlueScreenView no se descarga o extrae?<br \/>\nR: Si hay alg\u00fan problema, el script saldr\u00e1 con un c\u00f3digo de error 2. Aseg\u00farate de tener una conexi\u00f3n a Internet estable y permisos suficientes.<\/li>\n<li><strong>P:<\/strong> \u00bfC\u00f3mo puedo utilizar el script en versiones anteriores de Windows?<br \/>\nR: Aunque el script est\u00e1 dise\u00f1ado para versiones m\u00e1s recientes, es posible que tengas que modificar ciertos par\u00e1metros o integrar utilidades antiguas para que sea compatible con versiones anteriores de Windows.<\/li>\n<\/ul>\n<h2>Implicaciones para la seguridad<\/h2>\n<p>Las BSOD no son solamente molestas; pueden ser un problema de seguridad. Una BSOD recurrente puede ser se\u00f1al de que una entidad maliciosa intenta comprometer el sistema. Al registrar y analizar estos eventos, los profesionales de TI pueden identificar posibles amenazas y garantizar la seguridad del sistema.<\/p>\n<h2>Recomendaciones<\/h2>\n<ul>\n<li>Aseg\u00farate de ejecutar el script con privilegios de administrador para garantizar su plena funcionalidad.<\/li>\n<li>Actualiza peri\u00f3dicamente la herramienta BlueScreenView para poder usar las \u00faltimas funciones y garantizar la compatibilidad.<\/li>\n<li>Supervisa los sistemas en busca de BSOD recurrentes, ya que podr\u00edan indicar problemas de seguridad m\u00e1s profundos.<\/li>\n<\/ul>\n<h2>Reflexiones finales<\/h2>\n<p>En el din\u00e1mico mundo de las TI, herramientas como NinjaOne, cuando se combinan con scripts como el que hemos visto, permiten a los profesionales mantener la salud y la seguridad del sistema. Detectar y analizar los registros de BSOD y los cierres inesperados se convierte en un proceso simplificado, que garantiza la eficacia y la seguridad de las operaciones.<\/p>\n","protected":false},"author":35,"featured_media":207077,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","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":[4262],"class_list":["post-208623","script_hub","type-script_hub","status-publish","has-post-thumbnail","hentry","script_hub_category-windows"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/script_hub\/208623","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=208623"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/media\/207077"}],"wp:attachment":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/media?parent=208623"}],"wp:term":[{"taxonomy":"script_hub_category","embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/operating_system?post=208623"},{"taxonomy":"use_cases","embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/use_cases?post=208623"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}