{"id":353750,"date":"2024-09-17T10:20:08","date_gmt":"2024-09-17T10:20:08","guid":{"rendered":"https:\/\/www.ninjaone.com\/script-hub\/automatizzare-microsoft-safety-scanner\/"},"modified":"2024-10-13T19:04:16","modified_gmt":"2024-10-13T19:04:16","slug":"automatizzare-microsoft-safety-scanner","status":"publish","type":"script_hub","link":"https:\/\/www.ninjaone.com\/it\/script-hub\/automatizzare-microsoft-safety-scanner\/","title":{"rendered":"Come automatizzare Microsoft Safety Scanner utilizzando uno script PowerShell"},"content":{"rendered":"<p>Nell&#8217;odierno panorama IT attento alla sicurezza, garantire che i sistemi rimangano liberi da malware e altre minacce \u00e8 una priorit\u00e0 assoluta per i professionisti IT e i <a href=\"https:\/\/www.ninjaone.com\/it\/cos-e-un-msp\" target=\"_blank\" rel=\"noopener\">Managed Service Provider (MSP)<\/a>. Sebbene siano disponibili diversi strumenti per raggiungere questo obiettivo, l&#8217;automazione del rilevamento e della risposta alle minacce pu\u00f2 ridurre in modo significativo il tempo e l&#8217;impegno necessari per mantenere un ambiente sicuro.<\/p>\n<p>Uno di questi strumenti che pu\u00f2 essere integrato in un flusso di lavoro automatizzato \u00e8 <a href=\"https:\/\/learn.microsoft.com\/en-us\/defender-endpoint\/safety-scanner-download\" target=\"_blank\" rel=\"noopener\">Microsoft Safety Scanner (MSERT)<\/a>. In questo post analizzeremo uno script PowerShell che\u00a0<strong>automatizza il download, l&#8217;esecuzione e la creazione di report di MSERT<\/strong>, rendendo pi\u00f9 semplice per i professionisti IT mantenere i propri sistemi sicuri.<\/p>\n<h2>Background<\/h2>\n<p>Microsoft Safety Scanner \u00e8 uno strumento gratuito di scansione on-demand progettato per rilevare e <a href=\"https:\/\/www.ninjaone.com\/it\/blog\/5-passi-per-rimuovere-il-malware-dal-computer\/\" target=\"_blank\" rel=\"noopener\">rimuovere i malware<\/a> dai sistemi Windows. Viene aggiornato frequentemente ed \u00e8 progettato per essere utilizzato in ambienti in cui sono necessarie le definizioni di sicurezza pi\u00f9 recenti, ma in cui una soluzione always-on potrebbe non essere possibile da implementare.<\/p>\n<p>Lo script per automatizzare Microsoft Safety Scanner di cui parleremo in questo post semplifica il processo di utilizzo di MSERT automatizzandone il download, l&#8217;esecuzione e la gestione dei risultati. \u00c8 particolarmente utile negli ambienti in cui \u00e8 necessario effettuare scansioni regolari, ma dove non risulta pratico intervenire manualmente.<\/p>\n<p>Per i professionisti IT e gli MSP, la possibilit\u00e0 di automatizzare Microsoft Safety Scanner riduce il rischio di errori umani, garantisce la coerenza delle modalit\u00e0 di esecuzione delle scansioni e libera tempo prezioso per altre attivit\u00e0. Questo script \u00e8 uno strumento potente per <a href=\"https:\/\/www.ninjaone.com\/it\/gestione-impresa\/sicurezza\/\" target=\"_blank\" rel=\"noopener\">mantenere un ambiente IT sicuro<\/a> con il minimo sforzo.<\/p>\n<h2>Lo script per automatizzare 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>Analisi dettagliata<\/h2>\n<p>Lo script PowerShell fornito \u00e8 progettato per automatizzare diverse attivit\u00e0 chiave relative all&#8217;esecuzione di Microsoft Safety Scanner:<\/p>\n<ol>\n<li><strong>Gestione dei parametri<\/strong>: Lo script per automatizzare Microsoft Safety Scanner inizia definendo i parametri per il tipo di scansione (rapida o completa), un periodo di timeout e un campo personalizzato opzionale in cui salvare i risultati. Questi parametri sono impostati con valori predefiniti, ma possono anche essere sovrascritti da variabili d&#8217;ambiente, consentendo un uso flessibile in diversi scenari.<\/li>\n<li><strong>Impostazione dell&#8217;ambiente<\/strong>: Prima di procedere, lo script per automatizzare Microsoft Safety Scanner controlla che l&#8217;utente abbia i privilegi amministrativi necessari. In mancanza di questi, lo script si interrompe, garantendo che solo il personale autorizzato possa eseguire scansioni che potrebbero potenzialmente interrompere i flussi di lavoro.<\/li>\n<li><strong>Download del file<\/strong>: Una delle funzioni principali dello script per automatizzare Microsoft Safety Scanner \u00e8 scaricare l&#8217;ultima versione di MSERT dai server di Microsoft. Questa azione viene gestita dalla funzione Invoke-Download, che supporta TLS 1.2 e 1.3 per le connessioni sicure. La funzione tenta di scaricare il file pi\u00f9 volte per tenere conto di eventuali problemi di rete o di limitazione della velocit\u00e0 da parte del server.<\/li>\n<li><strong>Esecuzione della scansione<\/strong>: Una volta scaricato, lo script per automatizzare Microsoft Safety Scanner avvia la scansione utilizzando i parametri specificati. Pu\u00f2 eseguire una scansione rapida delle posizioni pi\u00f9 comuni degli exploit o una scansione completa dell&#8217;intero disco, a seconda della scelta dell&#8217;utente. La scansione viene eseguita in modalit\u00e0 silenziosa per ridurre al minimo le interruzioni.<\/li>\n<li><strong>Gestione dei risultati<\/strong>: Al termine della scansione, lo script elabora il file di log generato da MSERT. Verifica la presenza di eventuali minacce rilevate e stampa i risultati nella console. Se specificato, salva anche i risultati in un campo personalizzato all&#8217;interno di NinjaOne, che pu\u00f2 essere utilizzato per ulteriori analisi o report.<\/li>\n<li><strong>Pulizia<\/strong>: Infine, lo script rimuove l&#8217;eseguibile MSERT scaricato e il file di log per ripulire il sistema, assicurandosi che non vengano lasciati file inutili.<\/li>\n<\/ol>\n<h2>Casi d&#8217;uso potenziali<\/h2>\n<p>Immagina uno scenario in cui un MSP \u00e8 responsabile della sicurezza di centinaia di endpoint di pi\u00f9 clienti. Eseguire manualmente le scansioni del malware su ogni computer sarebbe dispendioso in termini di tempo e inefficiente.<\/p>\n<p>Distribuendo su tutti gli endpoint questo script per automatizzare Microsoft Safety Scanner, l&#8217;MSP pu\u00f2 garantire che ogni sistema venga regolarmente sottoposto a scansione alla ricerca di minacce, con i risultati riportati automaticamente nella console di gestione. Se viene rilevata una minaccia, l&#8217;MSP pu\u00f2 rispondere rapidamente, riducendo al minimo il danno potenziale e mantenendo un ambiente sicuro per i propri clienti.<\/p>\n<h2>Confronti<\/h2>\n<p>L&#8217;approccio utilizzato in questo script per automatizzare Microsoft Safety Scanner \u00e8 diverso rispetto ai metodi tradizionali e manuali di esecuzione dello strumento Microsoft. Tradizionalmente, un professionista dell&#8217;IT dovrebbe scaricare MSERT, eseguirlo manualmente e poi esaminare i risultati, operazioni che sono soggette a sviste e incoerenze.<\/p>\n<p>Automatizzando il processo con PowerShell, lo script assicura che le scansioni vengano eseguite in modo uniforme e regolare, <a href=\"https:\/\/www.ninjaone.com\/it\/blog\/come-l-errore-umano-influisce-sui-rischi-di-cybersecurity\/\" target=\"_blank\" rel=\"noopener\">riducendo la possibilit\u00e0 di errore umano<\/a> e garantendo che i protocolli di sicurezza vengano seguiti in modo coerente.<\/p>\n<p>Rispetto ad altre soluzioni automatizzate, come un software antivirus completo con protezione in tempo reale, questo script per automatizzare Microsoft Safety Scanner offre un&#8217;alternativa leggera e on-demand che pu\u00f2 essere integrata in pratiche di sicurezza pi\u00f9 ampie. \u00c8 particolarmente utile negli ambienti in cui l&#8217;esecuzione di un software antivirus completo su ogni computer potrebbe non essere attuabile o necessaria.<\/p>\n<h2>Domande frequenti<\/h2>\n<p>1.\u00a0<strong>Cosa succede se lo script per automatizzare Microsoft Safety Scanner si interrompe durante una scansione?<\/strong><br \/>\nSe la scansione supera il periodo di timeout specificato, lo script termina il processo ed emette un avviso. In questo modo si evita che la scansione venga eseguita all&#8217;infinito, con un potenziale impatto sulle prestazioni del sistema.<\/p>\n<p>2.<strong>\u00a0Lo script pu\u00f2 essere utilizzato su versioni precedenti di Windows?<\/strong><br \/>\nLo script per automatizzare Microsoft Safety Scanner richiede almeno Windows 10 o Server 2016. Le versioni pi\u00f9 vecchie di Windows potrebbero non supportare alcune delle funzioni utilizzate nello script, come TLS 1.2\/1.3 o alcuni cmdlet PowerShell.<\/p>\n<p>3.\u00a0<strong>Come gestisce lo script i problemi di rete durante il download?<\/strong><br \/>\nLa funzione Invoke-Download prevede pi\u00f9 tentativi di scaricare l&#8217;eseguibile MSERT. Se il download non riesce dopo diversi tentativi, lo script genera un errore e termina.<\/p>\n<p>4.<strong>\u00a0\u00c8 sicuro eseguire questo script in un ambiente di produzione?<\/strong><br \/>\nS\u00ec, lo script per automatizzare Microsoft Safety Scanner \u00e8 stato progettato tenendo conto della sicurezza, con controlli dei privilegi amministrativi e un&#8217;attenta gestione dei potenziali errori. Tuttavia, \u00e8 sempre consigliabile testare gli script in un ambiente controllato prima di distribuirli su larga scala.<\/p>\n<h2>Implicazioni<\/h2>\n<p>I risultati di questo script per automatizzare Microsoft Safety Scanner possono avere implicazioni significative per la sicurezza informatica. Automatizzando le scansioni di <a href=\"https:\/\/www.ninjaone.com\/it\/blog\/le-migliori-soluzioni-per-proteggersi-dai-malware\/\" target=\"_blank\" rel=\"noopener\">malware<\/a>, i team IT possono garantire che i sistemi vengano controllati regolarmente per individuare le minacce, riducendo il rischio di infezioni non rilevate. Questo approccio proattivo alla sicurezza pu\u00f2 aiutare a prevenire <a href=\"https:\/\/www.ninjaone.com\/it\/it-hub\/sicurezza-degli-endpoint\/cos-e-una-violazione-dei-dati\/\" target=\"_blank\" rel=\"noopener\">le violazioni dei dati<\/a> e altri incidenti di sicurezza, che potrebbero avere gravi conseguenze per le aziende, tra cui perdite finanziarie e danni alla reputazione.<\/p>\n<h2>Raccomandazioni<\/h2>\n<p>Quando utilizzi questo script per automatizzare Microsoft Safety Scanner, tieni a mente le seguenti best practice:<\/p>\n<ul>\n<li><strong>Testa lo script in un ambiente controllato<\/strong>\u00a0prima di distribuirlo su tutti gli endpoint, per assicurarti che funzioni come previsto.<\/li>\n<li><strong>Pianifica scansioni regolari<\/strong>\u00a0utilizzando Windows Task Scheduler o un altro strumento di automazione, per garantire un monitoraggio continuo dei sistemi.<\/li>\n<li><strong>Monitora i risultati<\/strong>\u00a0attentamente e imposta degli avvisi quando vengono rilevate delle minacce, in modo da poter rispondere rapidamente.<\/li>\n<\/ul>\n<h2>Considerazioni finali<\/h2>\n<p>Questo script PowerShell offre un modo efficace per automatizzare Microsoft Safety Scanner, fornendo ai professionisti IT e agli MSP uno strumento affidabile per mantenere la sicurezza del sistema. Integrandolo in pratiche di sicurezza pi\u00f9 ampie, gli utenti possono garantire che i loro ambienti rimangano <a href=\"https:\/\/www.ninjaone.com\/it\/blog\/le-migliori-soluzioni-per-proteggersi-dai-malware\/\" target=\"_blank\" rel=\"noopener\">protetti dalle minacce malware<\/a> con un intervento manuale minimo.<\/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":[4274],"class_list":["post-353750","script_hub","type-script_hub","status-publish","hentry","script_hub_category-windows"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/script_hub\/353750","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/script_hub"}],"about":[{"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/types\/script_hub"}],"author":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/users\/35"}],"replies":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/comments?post=353750"}],"wp:attachment":[{"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/media?parent=353750"}],"wp:term":[{"taxonomy":"script_hub_category","embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/operating_system?post=353750"},{"taxonomy":"use_cases","embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/use_cases?post=353750"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}