{"id":353803,"date":"2024-10-07T09:27:51","date_gmt":"2024-10-07T09:27:51","guid":{"rendered":"https:\/\/www.ninjaone.com\/script-hub\/microsoft-safety-scanner\/"},"modified":"2024-10-13T19:04:12","modified_gmt":"2024-10-13T19:04:12","slug":"microsoft-safety-scanner","status":"publish","type":"script_hub","link":"https:\/\/www.ninjaone.com\/es\/script-hub\/microsoft-safety-scanner\/","title":{"rendered":"C\u00f3mo automatizar Microsoft Safety Scanner mediante un script PowerShell"},"content":{"rendered":"<p>En el actual panorama inform\u00e1tico, tan preocupado por la seguridad, garantizar que los sistemas permanezcan libres de malware y otras amenazas es una prioridad absoluta para los profesionales de TI y los <a href=\"https:\/\/www.ninjaone.com\/es\/que-es-un-msp\" target=\"_blank\" rel=\"noopener\">proveedores de servicios gestionados (MSP)<\/a>. Aunque existen varias herramientas para lograrlo, la automatizaci\u00f3n de la detecci\u00f3n y respuesta a las amenazas puede reducir significativamente el tiempo y el esfuerzo necesarios para mantener un entorno seguro.<\/p>\n<p>Una de estas herramientas, que puede integrarse en un flujo de trabajo automatizado, es el <a href=\"https:\/\/learn.microsoft.com\/en-us\/defender-endpoint\/safety-scanner-download\" target=\"_blank\" rel=\"noopener\">Microsoft Safety Scanner (MSERT)<\/a>. En este post, exploraremos un script PowerShell que\u00a0<strong>automatiza la descarga, ejecuci\u00f3n y generaci\u00f3n de informes de Microsoft Safety Scanner<\/strong>, facilitando a los profesionales de TI el mantenimiento de la seguridad de sus sistemas.<\/p>\n<h2>Contexto<\/h2>\n<p>Microsoft Safety Scanner es una herramienta gratuita de an\u00e1lisis on-demand dise\u00f1ada para detectar y <a href=\"https:\/\/www.ninjaone.com\/blog\/5-steps-for-removing-malware-from-your-computer\/\" target=\"_blank\" rel=\"noopener\">eliminar malware<\/a> de sistemas Windows. Se actualiza con frecuencia y est\u00e1 pensada para entornos en los que se requieren las \u00faltimas definiciones de seguridad, pero en los que una soluci\u00f3n siempre activa puede no ser factible.<\/p>\n<p>El script del que hablaremos en este post agiliza el proceso de uso de MSERT automatizando su descarga, ejecuci\u00f3n y gesti\u00f3n de resultados. Esto resulta especialmente \u00fatil en entornos en los que es necesario realizar exploraciones peri\u00f3dicas pero la intervenci\u00f3n manual resulta poco pr\u00e1ctica.<\/p>\n<p>Para los profesionales de TI y los MSP, la posibilidad de automatizar este proceso reduce el riesgo de error humano, garantiza la coherencia en la ejecuci\u00f3n de las exploraciones y deja un tiempo valioso para otras tareas. Este script es una poderosa herramienta para <a href=\"https:\/\/www.ninjaone.com\/es\/enterprise-it-management\/seguridad\/\" target=\"_blank\" rel=\"noopener\">mantener un entorno de TI seguro<\/a> con el m\u00ednimo esfuerzo.<\/p>\n<h2>El script para automatizar Microsoft Safety Scanner<\/h2>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\">#Requires -Version 5.1\r\n\r\n&lt;#\r\n.SYNOPSIS\r\n    Run the Microsoft Safety Scanner, collect the results, and optionally save the results to a multiline custom field.\r\n.DESCRIPTION\r\n    Run the Microsoft Safety Scanner, collect the results, and optionally save the results to a multiline custom field.\r\n.EXAMPLE\r\n    (No Parameters)\r\n    \r\n    Downloading MSERT from https:\/\/go.microsoft.com\/fwlink\/?LinkId=212732\r\n    Waiting for 3 seconds.\r\n    Download Attempt 1\r\n    Download Successful!\r\n    Initiating Scan\r\n    Exit Code: 7\r\n    [Critical] Infections found!\r\n\r\n    ---------------------------------------------------------------------------------------\r\n    Microsoft Safety Scanner v1.405, (build 1.405.445.0)\r\n    Started On Thu Feb 22 13:33:34 2024\r\n\r\n    Engine: 1.1.24010.10\r\n    Signatures: 1.405.445.0\r\n    MpGear: 1.1.16330.1\r\n    Run Mode: Scan Run in Quiet Mode\r\n\r\n    Quick Scan Results:\r\n    -------------------\r\n    Threat Detected: Virus:DOS\/EICAR_Test_File, not removed.\r\n        Action: NoAction, Result: 0x00000000\r\n            file:\/\/C:\\Windows\\system32\\eicarcom2.zip-&gt;eicar_com.zip-&gt;eicar.com\r\n                SigSeq: 0x00000555DC2DDDB0\r\n            file:\/\/C:\\Windows\\system32\\eicar.com\r\n                SigSeq: 0x00000555DC2DDDB0\r\n            file:\/\/C:\\Windows\\eicar.com\r\n                SigSeq: 0x00000555DC2DDDB0\r\n            containerfile:\/\/C:\\Windows\\system32\\eicarcom2.zip\r\n\r\n    Results Summary:\r\n    ----------------\r\n    Found Virus:DOS\/EICAR_Test_File, not removed.\r\n    Successfully Submitted MAPS Report\r\n    Successfully Submitted Heartbeat Report\r\n    Microsoft Safety Scanner Finished On Thu Feb 22 13:35:58 2024\r\n\r\n\r\n    Return code: 7 (0x7)\r\n\r\nPARAMETER: -ScanType \"Full\"\r\n    Specifies the type of scan to perform. \"Full\" for a complete disk scan, or \"Quick\" for a scan of common exploit locations.\r\n\r\nPARAMETER: -Timeout \"ReplaceMeWithANumber\"\r\n    Sets a time limit for the scan in minutes. If the scan exceeds this duration, it is canceled, and an error is output. Replace \"ReplaceMeWithANumber\" with the desired time limit in minutes.\r\n\r\nPARAMETER: -CustomField \"ReplaceWithNameOfCustomField\"\r\n    Specifies the name of the multiline custom field where scan results are optionally saved. Enter the field name to enable this feature.\r\n.OUTPUTS\r\n    None\r\n.NOTES\r\n    Minimum OS Architecture Supported: Windows 10, 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]$ScanType = \"Quick\",\r\n    [Parameter()]\r\n    [Int]$Timeout = 30,\r\n    [Parameter()]\r\n    [String]$CustomField,\r\n    [Parameter()]\r\n    [String]$DownloadURL = \"https:\/\/go.microsoft.com\/fwlink\/?LinkId=212732\"\r\n)\r\n\r\nbegin {\r\n    # Set parameters using dynamic script variables.\r\n    if($env:scanType -and $env:scanType -notlike \"null\"){ $ScanType = $env:scanType }\r\n    if($env:scanTimeoutInMinutes -and $env:scanTimeoutInMinutes -notlike \"null\"){ $Timeout = $env:scanTimeoutInMinutes }\r\n    if($env:customFieldName -and $env:customFieldName -notlike \"null\"){ $CustomField = $env:customFieldName }\r\n\r\n    # If a timeout is specified, check that it's in the valid range.\r\n    if($Timeout -lt 1 -or $Timeout -ge 120){\r\n        Write-Host \"[Error] Timeout must be greater than or equal to 1 minute and less than 120 minutes.\"\r\n        exit 1\r\n    }\r\n\r\n    # If we're not given a scan type, error out.\r\n    if(-not $ScanType){\r\n        Write-Host \"[Error] Please select a scan type (Quick or Full).\"\r\n        exit 1\r\n    }\r\n\r\n    # Check that the scan type is valid.\r\n    switch($ScanType){\r\n        \"Quick\" { Write-Verbose \"Quick Scan Selected!\"}\r\n        \"Full\" { Write-Verbose \"Full Scan Selected!\" }\r\n        default { \r\n            Write-Host \"[Error] Invalid scan type selected!\"\r\n            exit 1\r\n        }\r\n    } \r\n\r\n    # Checks for local administrator rights.\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    # Utility function for downloading files.\r\n    function Invoke-Download {\r\n        param(\r\n            [Parameter()]\r\n            [String]$URL,\r\n            [Parameter()]\r\n            [String]$Path,\r\n            [Parameter()]\r\n            [int]$Attempts = 3,\r\n            [Parameter()]\r\n            [Switch]$SkipSleep\r\n        )\r\n\r\n        $SupportedTLSversions = [enum]::GetValues('Net.SecurityProtocolType')\r\n        if ( ($SupportedTLSversions -contains 'Tls13') -and ($SupportedTLSversions -contains 'Tls12') ) {\r\n            [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol::Tls13 -bor [System.Net.SecurityProtocolType]::Tls12\r\n        }\r\n        elseif ( $SupportedTLSversions -contains 'Tls12' ) {\r\n            [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12\r\n        }\r\n        else {\r\n            # Not everything requires TLS 1.2, but we'll try anyway.\r\n            Write-Warning \"TLS 1.2 and or TLS 1.3 are not supported on this system. This download may fail!\"\r\n            if ($PSVersionTable.PSVersion.Major -lt 3) {\r\n                Write-Warning \"PowerShell 2 \/ .NET 2.0 doesn't support TLS 1.2.\"\r\n            }\r\n        }\r\n\r\n        $i = 1\r\n        While ($i -le $Attempts) {\r\n            # Some cloud services have rate-limiting\r\n            if (-not ($SkipSleep)) {\r\n                $SleepTime = Get-Random -Minimum 3 -Maximum 15\r\n                Write-Host \"Waiting for $SleepTime seconds.\"\r\n                Start-Sleep -Seconds $SleepTime\r\n            }\r\n        \r\n            if ($i -ne 1) { Write-Host \"\" }\r\n            Write-Host \"Download Attempt $i\"\r\n\r\n            $PreviousProgressPreference = $ProgressPreference\r\n            $ProgressPreference = 'SilentlyContinue'\r\n            try {\r\n                # Invoke-WebRequest is preferred because it supports links that redirect, e.g., https:\/\/t.ly\r\n                if ($PSVersionTable.PSVersion.Major -lt 4) {\r\n                    # Downloads the file\r\n                    $WebClient = New-Object System.Net.WebClient\r\n                    $WebClient.DownloadFile($URL, $Path)\r\n                }\r\n                else {\r\n                    # Standard options\r\n                    $WebRequestArgs = @{\r\n                        Uri                = $URL\r\n                        OutFile            = $Path\r\n                        MaximumRedirection = 10\r\n                        UseBasicParsing    = $true\r\n                    }\r\n\r\n                    # Downloads the file\r\n                    Invoke-WebRequest @WebRequestArgs\r\n                }\r\n\r\n                $ProgressPreference = $PreviousProgressPreference\r\n                $File = Test-Path -Path $Path -ErrorAction SilentlyContinue\r\n            }\r\n            catch {\r\n                Write-Warning \"An error has occurred while downloading!\"\r\n                Write-Warning $_.Exception.Message\r\n\r\n                if (Test-Path -Path $Path -ErrorAction SilentlyContinue) {\r\n                    Remove-Item $Path -Force -Confirm:$false -ErrorAction SilentlyContinue\r\n                }\r\n\r\n                $File = $False\r\n            }\r\n\r\n            if ($File) {\r\n                $i = $Attempts\r\n            }\r\n            else {\r\n                Write-Warning \"File failed to download.\"\r\n                Write-Host \"\"\r\n            }\r\n\r\n            $i++\r\n        }\r\n\r\n        if (-not (Test-Path -Path $Path)) {\r\n            [PSCustomObject]@{\r\n                ExitCode = 1\r\n            }\r\n        }\r\n        else {\r\n            [PSCustomObject]@{\r\n                ExitCode = 0\r\n            }\r\n        }\r\n    }\r\n\r\n    # Utility function to help set custom fields\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 | Measure-Object -Character | Select-Object -ExpandProperty Characters\r\n        if($Characters -ge 10000){\r\n            throw [System.ArgumentOutOfRangeException]::New(\"Character limit exceeded, value is greater than 10,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  Date-Time to be in Unix Epoch time so we'll convert it here.\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 = Ninja-Property-Set -Name $Name -Value $NinjaValue 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    $ExitCode = 0\r\n\r\n    # If the log file already exists remove it.\r\n    if(Test-Path -Path \"$env:SYSTEMROOT\\debug\\msert.log\"){\r\n        Remove-Item -Path \"$env:SYSTEMROOT\\debug\\msert.log\" -Force -ErrorAction SilentlyContinue\r\n    }\r\n}\r\nprocess {\r\n    # Error out if we don't have local admin permissions.\r\n    if (-not (Test-IsElevated)) {\r\n        Write-Host \"[Error] Access Denied. Please run with Administrator privileges.\"\r\n        exit 1\r\n    }\r\n\r\n    # Download MSERT.\r\n    Write-Host \"Downloading MSERT from $DownloadURL\"\r\n    $MSERTPath = \"$env:TEMP\\MSERT.exe\"\r\n    $Download = Invoke-Download -Path $MSERTPath -URL $DownloadURL\r\n    if($Download.ExitCode -ne 0){\r\n        Write-Host \"[Error] Failed to download MSERT please check that $DownloadURL is reachable!\"\r\n        exit 1\r\n    }\r\n\r\n    Write-Host \"Download Successful!\"\r\n\r\n    # Start the MSERT Scan with the parameters given.\r\n    Write-Host \"Initiating Scan\"\r\n    $Arguments = New-Object System.Collections.Generic.List[string]\r\n    if($ScanType -eq \"Full\"){\r\n        $Arguments.Add(\"\/F\")\r\n    }\r\n    $Arguments.Add(\"\/Q\")\r\n    $Arguments.Add(\"\/N\")\r\n\r\n    try{\r\n        # Run it with our specified timeout.\r\n        $TimeoutInSeconds = $Timeout * 60\r\n        $MSERTProcess = Start-Process -FilePath $MSERTPath -ArgumentList $Arguments -NoNewWindow -PassThru\r\n        $MSERTProcess | Wait-Process -Timeout $TimeoutInSeconds -ErrorAction Stop\r\n    }catch{\r\n        Write-Host \"[Alert] The Microsoft Safety Scanner exceeded the specified timeout of $Timeout minutes, and the script is now terminating.\"\r\n        $MSERTProcess | Stop-Process -Force\r\n        $TimedOut = $True\r\n        $ExitCode = 1\r\n    }\r\n    Write-Host \"Exit Code: $($MSERTProcess.ExitCode)\"\r\n\r\n    # If the report is missing, something has clearly gone wrong.\r\n    if(-not (Test-Path -Path $env:SYSTEMROOT\\debug\\msert.log)){\r\n        Write-Host \"[Error] The report from MSERT.exe is missing?\"\r\n        exit 1\r\n    }\r\n\r\n    # Get the contents of the MSERT log and error out if it's blank.\r\n    $Report = Get-Content -Path \"$env:SYSTEMROOT\\debug\\msert.log\"\r\n    if(-not $Report){\r\n        Write-Host \"[Error] The report from MSERT.exe is empty?\"\r\n        exit 1\r\n    }\r\n\r\n    # If threats are detected, send out the alert.\r\n    $Report | ForEach-Object {\r\n        if($_ -match \"No infection found\"){\r\n            $NoInfectionFoundTextPresent = $True\r\n        }\r\n\r\n        if($_ -match \"Threat Detected\" ){\r\n            $ThreatDetectedTextPresent = $True\r\n        }\r\n    }\r\n\r\n    \r\n    if(($ThreatDetectedTextPresent -or -not $NoInfectionFoundTextPresent) -and -not $TimedOut){\r\n        Write-Host \"[Critical] Infections found!\"\r\n    }elseif($ExitCode -ne 1 -and -not $TimedOut){\r\n        Write-Host \"[Success] Scan has completed no infections detected.\"\r\n    }\r\n\r\n    # Save to a custom field upon request.\r\n    if($CustomField){\r\n        try {\r\n            Write-Host \"Attempting to set Custom Field '$CustomField'.\"\r\n            Set-NinjaProperty -Name $CustomField -Value ($Report | Out-String)\r\n            Write-Host \"Successfully set Custom Field '$CustomField'!\"\r\n        }\r\n        catch {\r\n            if($_.Exception.Message){\r\n                Write-Host \"[Error] $($_.Exception.Message)\"\r\n            }\r\n\r\n            if($_.Message){\r\n                Write-Host \"[Error] $($_.Message)\"\r\n            }\r\n\r\n            $ExitCode = 1\r\n        }\r\n    }\r\n\r\n    # Send out the report to the activity log.\r\n    $Report | Write-Host\r\n\r\n    # Remove the old log file.\r\n    if(Test-Path -Path \"$env:SYSTEMROOT\\debug\\msert.log\"){\r\n        Remove-Item -Path \"$env:SYSTEMROOT\\debug\\msert.log\" -Force -ErrorAction SilentlyContinue\r\n    }\r\n\r\n    # Exit.\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>An\u00e1lisis detallado<\/h2>\n<p>El script PowerShell proporcionado est\u00e1 dise\u00f1ado para automatizar varias tareas clave relacionadas con la ejecuci\u00f3n de Microsoft Safety Scanner:<\/p>\n<ol>\n<li><strong>Gesti\u00f3n de par\u00e1metros<\/strong>: el script comienza definiendo par\u00e1metros para el tipo de escaneo (R\u00e1pido o Completo), un per\u00edodo de tiempo de espera y un campo personalizado opcional donde se pueden guardar los resultados. Estos par\u00e1metros se establecen por defecto, pero tambi\u00e9n pueden ser anulados por variables de entorno, lo que permite un uso flexible en diferentes escenarios.<\/li>\n<li><strong>Configuraci\u00f3n del entorno<\/strong>: antes de continuar, el script comprueba si el usuario tiene los privilegios administrativos necesarios. Sin ellos, el script terminar\u00e1, asegurando que s\u00f3lo el personal autorizado pueda ejecutar escaneos potencialmente perjudiciales.<\/li>\n<li><strong>Descarga de archivos<\/strong>: una de las principales funciones del script es descargar la \u00faltima versi\u00f3n de MSERT de los servidores de Microsoft. De ello se encarga la funci\u00f3n Invoke-Download, que admite TLS 1.2 y 1.3 para conexiones seguras. La funci\u00f3n intenta descargar el archivo varias veces para tener en cuenta cualquier problema de red o limitaci\u00f3n de velocidad por parte del servidor.<\/li>\n<li><strong>Ejecuci\u00f3n de la exploraci\u00f3n<\/strong>: una vez descargado, el script inicia el escaneo utilizando los par\u00e1metros especificados. Puede realizar un escaneo r\u00e1pido de las ubicaciones m\u00e1s comunes de los exploits o un escaneo completo de todo el disco, dependiendo de la elecci\u00f3n del usuario. La exploraci\u00f3n se realiza en modo silencioso para minimizar las interrupciones.<\/li>\n<li><strong>Resultados de la gesti\u00f3n<\/strong>: una vez finalizado el an\u00e1lisis, el script procesa el archivo de registro generado por MSERT. Comprueba si se ha detectado alguna amenaza e imprime los resultados en la consola. Si se especifica, tambi\u00e9n guarda los resultados en un campo personalizado dentro de NinjaOne, que puede ser utilizado para su posterior an\u00e1lisis o presentaci\u00f3n de informes.<\/li>\n<li><strong>Limpieza<\/strong>: por \u00faltimo, el script elimina el ejecutable MSERT descargado y el archivo de registro para limpiar el sistema, asegur\u00e1ndose de que no quedan archivos innecesarios.<\/li>\n<\/ol>\n<h2>Posibles casos de uso<\/h2>\n<p>Imag\u00ednate una situaci\u00f3n en la que un MSP es responsable de la seguridad de cientos de endpoints de varios clientes. Ejecutar manualmente an\u00e1lisis de malware en cada m\u00e1quina llevar\u00eda mucho tiempo y ser\u00eda ineficaz.<\/p>\n<p>Al desplegar este script en todos los endpoints, el MSP puede garantizar que cada sistema se analice peri\u00f3dicamente en busca de amenazas y que los resultados se comuniquen autom\u00e1ticamente a su consola de gesti\u00f3n. Si se detecta una amenaza, el MSP puede responder r\u00e1pidamente, minimizando el da\u00f1o potencial y manteniendo un entorno seguro para sus clientes.<\/p>\n<h2>Comparaciones<\/h2>\n<p>El enfoque utilizado en este script para automatizar Microsoft Safety Scanner contrasta con los m\u00e9todos manuales tradicionales de ejecuci\u00f3n de MSERT. Normalmente, un profesional de TI tendr\u00eda que descargar MSERT, ejecutarlo manualmente y luego revisar los resultados, pasos propensos a descuidos e incoherencias.<\/p>\n<p>Al automatizar el proceso con PowerShell, el script garantiza que las exploraciones se realicen de manera uniforme y regular, <a href=\"https:\/\/www.ninjaone.com\/blog\/how-human-error-relates-to-cybersecurity-risks\/\" target=\"_blank\" rel=\"noopener\">reduciendo la posibilidad de errores humanos<\/a> y asegurando que los protocolos de seguridad se sigan de manera coherente.<\/p>\n<p>En comparaci\u00f3n con otras soluciones automatizadas, como el software antivirus completo con protecci\u00f3n en tiempo real, este script para automatizar Microsoft Safety Scanner ofrece una alternativa ligera y on-demand que puede integrarse en pr\u00e1cticas de seguridad m\u00e1s amplias. Resulta especialmente \u00fatil en entornos en los que no es posible o necesario ejecutar un software antivirus completo en todos los equipos.<\/p>\n<h2>FAQ<\/h2>\n<p><strong>\u00bfQu\u00e9 ocurre si se agota el tiempo de espera del script durante una exploraci\u00f3n?<\/strong><br \/>\nSi el an\u00e1lisis supera el tiempo de espera especificado, el script finaliza el proceso y emite una alerta. Esto evita que la exploraci\u00f3n se ejecute indefinidamente y afecte potencialmente al rendimiento del sistema.<\/p>\n<p>2. <strong>\u00a0\u00bfSe puede utilizar el script en versiones anteriores de Windows?<\/strong><br \/>\nEl script requiere al menos Windows 10 o Server 2016. Es posible que las versiones antiguas de Windows no admitan algunas de las funciones utilizadas en el script, como TLS 1.2\/1.3 o determinados cmdlets de PowerShell.<\/p>\n<p>3.\u00a0<strong>\u00bfC\u00f3mo gestiona el script los problemas de red durante la descarga?<\/strong><br \/>\nLa funci\u00f3n Invoke-Download incluye m\u00faltiples intentos de descarga del ejecutable MSERT. Si la descarga falla tras varios intentos, el script mostrar\u00e1 un error y finalizar\u00e1.<\/p>\n<p>4. <strong>\u00a0\u00bfEs seguro ejecutar este script en un entorno de producci\u00f3n?<\/strong><br \/>\nS\u00ed, el script se ha dise\u00f1ado pensando en la seguridad, incluyendo comprobaciones de privilegios administrativos y un tratamiento cuidadoso de los posibles errores. Sin embargo, siempre es recomendable probar los scripts en un entorno controlado antes de desplegarlos ampliamente.<\/p>\n<h2>Implicaciones<\/h2>\n<p>Los resultados de este script para automatizar Microsoft Safety Scanner pueden tener importantes implicaciones para la seguridad inform\u00e1tica. Mediante la automatizaci\u00f3n de los an\u00e1lisis de <a href=\"https:\/\/www.ninjaone.com\/es\/blog\/mejores-soluciones-de-proteccion-contra-malware\/\" target=\"_blank\" rel=\"noopener\">malware<\/a>, los equipos inform\u00e1ticos pueden garantizar que los sistemas se comprueban peri\u00f3dicamente en busca de amenazas, reduciendo el riesgo de infecciones no detectadas. Este enfoque proactivo de la seguridad puede ayudar a prevenir <a href=\"https:\/\/www.ninjaone.com\/es\/it-hub\/endpoint-security\/que-es-una-violacion-de-datos\" target=\"_blank\" rel=\"noopener\">las violaciones de datos<\/a> y otros incidentes de seguridad, que pueden tener graves consecuencias para las empresas, como p\u00e9rdidas financieras y da\u00f1os a la reputaci\u00f3n.<\/p>\n<h2>Recomendaciones<\/h2>\n<p>Cuando utilices este script para automatizar Microsoft Safety Scanner, ten en cuenta las siguientes pr\u00e1cticas recomendadas:<\/p>\n<ul>\n<li><strong>Prueba el script en un entorno de laboratorio<\/strong>\u00a0antes de desplegarlo en todos los endpoints para asegurarte de que funciona como se espera.<\/li>\n<li><strong>Programa escaneos regulares<\/strong>\u00a0utilizando el Programador de Tareas de Windows u otra herramienta de automatizaci\u00f3n para asegurarte de que los sistemas est\u00e1n continuamente monitorizados.<\/li>\n<li><strong>Supervisa de cerca los resultados<\/strong>\u00a0y establece alertas para cuando se detecten amenazas, de modo que puedas responder r\u00e1pidamente.<\/li>\n<\/ul>\n<h2>Reflexiones finales<\/h2>\n<p>Este script PowerShell ofrece una potente forma de automatizar el uso de Microsoft Safety Scanner, proporcionando a los profesionales de TI y MSP una herramienta fiable para mantener la seguridad del sistema. Al integrarlo en pr\u00e1cticas de seguridad m\u00e1s amplias, los usuarios pueden garantizar que sus entornos permanezcan <a href=\"https:\/\/www.ninjaone.com\/es\/blog\/mejores-soluciones-de-proteccion-contra-malware\/\" target=\"_blank\" rel=\"noopener\">protegidos contra las amenazas de malware<\/a> con una intervenci\u00f3n manual m\u00ednima.<\/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":[4264],"class_list":["post-353803","script_hub","type-script_hub","status-publish","hentry","script_hub_category-windows"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/script_hub\/353803","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=353803"}],"wp:attachment":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/media?parent=353803"}],"wp:term":[{"taxonomy":"script_hub_category","embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/operating_system?post=353803"},{"taxonomy":"use_cases","embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/use_cases?post=353803"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}