{"id":390644,"date":"2024-12-12T05:49:04","date_gmt":"2024-12-12T05:49:04","guid":{"rendered":"https:\/\/www.ninjaone.com\/?post_type=script_hub&#038;p=390644"},"modified":"2024-12-12T05:49:04","modified_gmt":"2024-12-12T05:49:04","slug":"cancellare-la-cache-del-browser-con-powershell","status":"publish","type":"script_hub","link":"https:\/\/www.ninjaone.com\/it\/script-hub\/cancellare-la-cache-del-browser-con-powershell\/","title":{"rendered":"Guida completa per cancellare la cache del browser con PowerShell\u00a0"},"content":{"rendered":"<p><span data-contrast=\"none\">La gestione della cache del browser \u00e8 un&#8217;attivit\u00e0 comune ma cruciale negli ambienti IT. La cache aiuta a migliorare l&#8217;esperienza dell&#8217;utente memorizzando i file temporanei, ma con il tempo pu\u00f2 diventare troppo pesante, causando problemi di archiviazione e ritardi nelle prestazioni. Per gli amministratori IT, in particolare quelli che gestiscono pi\u00f9 utenti in ambienti aziendali, <strong>cancellare la cache del browser<\/strong> manualmente pu\u00f2 essere poco pratico. \u00c8 qui che entrano in gioco gli script di PowerShell, che offrono una soluzione sistematica e scalabile.<\/span><span data-ccp-props=\"{&quot;134233117&quot;:false,&quot;134233118&quot;:false,&quot;335559738&quot;:240,&quot;335559739&quot;:240}\">\u00a0<\/span><\/p>\n<p><span data-contrast=\"none\">Lo script per cancellare la cache del browser fornito \u00e8 un esempio di come i professionisti IT possono gestire in modo efficiente le cache dei browser per i vari utenti attraverso i principali browser come Mozilla Firefox, Google Chrome e Microsoft Edge. Approfondiamo i suoi meccanismi, i casi d&#8217;uso e le best practice correlate.<\/span><span data-ccp-props=\"{&quot;134233117&quot;:false,&quot;134233118&quot;:false,&quot;335559738&quot;:240,&quot;335559739&quot;:240}\">\u00a0<\/span><\/p>\n<h2>Comprendere lo script <span data-contrast=\"none\">per cancellare la cache del browser<\/span> e la sua importanza<\/h2>\n<p><span data-contrast=\"none\">Questo script \u00e8 uno strumento versatile per cancellare la cache del browser sui sistemi Windows. Progettato per la flessibilit\u00e0, pu\u00f2:<\/span><span data-ccp-props=\"{&quot;134233117&quot;:false,&quot;134233118&quot;:false,&quot;335559738&quot;:240,&quot;335559739&quot;:240}\">\u00a0<\/span><\/p>\n<ul>\n<li><span data-contrast=\"none\">Cancellare la cache del browser per tutti gli utenti (quando viene eseguito con i privilegi di sistema).<\/span><span data-ccp-props=\"{&quot;134233117&quot;:false,&quot;134233118&quot;:false,&quot;335559738&quot;:0,&quot;335559739&quot;:0}\">\u00a0<\/span><\/li>\n<li><span data-contrast=\"none\">Agire su utenti specifici in base ai loro nomi utente.<\/span><span data-ccp-props=\"{&quot;134233117&quot;:false,&quot;134233118&quot;:false,&quot;335559738&quot;:0,&quot;335559739&quot;:0}\">\u00a0<\/span><\/li>\n<li><span data-contrast=\"none\">Gestire la cache per i singoli browser, tra cui Firefox, Chrome ed Edge.<\/span><span data-ccp-props=\"{&quot;134233117&quot;:false,&quot;134233118&quot;:false,&quot;335559738&quot;:0,&quot;335559739&quot;:0}\">\u00a0<\/span><\/li>\n<li><span data-contrast=\"none\">Chiudere forzatamente i processi del browser se sono in esecuzione.<\/span><span data-ccp-props=\"{&quot;134233117&quot;:false,&quot;134233118&quot;:false,&quot;335559738&quot;:0,&quot;335559739&quot;:0}\">\u00a0<\/span><\/li>\n<\/ul>\n<p><span data-contrast=\"none\">Per i <a href=\"https:\/\/www.ninjaone.com\/it\/cos-e-un-msp\/\">fornitori di servizi gestiti (MSP)<\/a> e gli amministratori IT, queste capacit\u00e0 sono importantissime. Lo script per cancellare la cache del browser semplifica la manutenzione ordinaria, garantisce prestazioni costanti del browser e pu\u00f2 persino ridurre i rischi per la sicurezza associati a dati obsoleti nella cache.<\/span><span data-ccp-props=\"{&quot;134233117&quot;:false,&quot;134233118&quot;:false,&quot;335559738&quot;:240,&quot;335559739&quot;:240}\">\u00a0<\/span><\/p>\n<h2>Lo script <span data-contrast=\"none\">per cancellare la cache del browser<\/span>:<\/h2>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\">#Requires -Version 5.1\r\n\r\n&lt;#\r\n.SYNOPSIS\r\n    Clear the browser cache for all users (when run as system), some users (when a user is specified), or just the current user (when run as current user) depending on how the script is run.\r\n.DESCRIPTION\r\n    Clear the browser cache for all users (when run as system), some users (when a user is specified), or just the current user (when run as current user) depending on how the script is run.\r\n\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.EXAMPLE\r\n    -Firefox -ForceCloseBrowsers\r\n    \r\n    WARNING: Running Mozilla Firefox processess detected.\r\n\r\n    Clearing browser cache for tuser1\r\n    Closing Mozilla Firefox processes for tuser1 as requested.\r\n    Clearing Mozilla Firefox's browser cache for tuser1.\r\n\r\n\r\n    Clearing browser cache for cheart\r\n    Closing Mozilla Firefox processes for cheart as requested.\r\n    Clearing Mozilla Firefox's browser cache for cheart.\r\n\r\nPARAMETER: -Usernames \"ReplaceWithYourDesiredUsername\"\r\n    Clear the browser cache for only this comma-separated list of users.\r\n\r\nPARAMETER: -Firefox\r\n    Clear the browser cache for Mozilla Firefox.\r\n\r\nPARAMETER: -Chrome\r\n    Clear the browser cache for Google Chrome.\r\n\r\nPARAMETER: -Edge\r\n    Clear the browser cache for Microsoft Edge.\r\n\r\nPARAMETER: -ForceCloseBrowsers\r\n    Force close the browser prior to clearing the browser cache.\r\n\r\n.NOTES\r\n    Minimum OS Architecture Supported: Windows 10, Windows Server 2016\r\n    Release Notes: Initial Release\r\n#&gt;\r\n\r\n[CmdletBinding()]\r\nparam (\r\n    [Parameter()]\r\n    [String]$Usernames,\r\n    [Parameter()]\r\n    [Switch]$Firefox = [System.Convert]::ToBoolean($env:mozillaFirefox),\r\n    [Parameter()]\r\n    [Switch]$Chrome = [System.Convert]::ToBoolean($env:googleChrome),\r\n    [Parameter()]\r\n    [Switch]$Edge = [System.Convert]::ToBoolean($env:microsoftEdge),\r\n    [Parameter()]\r\n    [Switch]$ForceCloseBrowsers = [System.Convert]::ToBoolean($env:forceCloseBrowsers)\r\n)\r\n\r\nbegin {\r\n    if ($env:usernames -and $env:usernames -notlike \"null\") { $Usernames = $env:usernames }\r\n\r\n    # Check if none of the browser checkboxes (Firefox, Chrome, Edge) are selected\r\n    if (!$Firefox -and !$Chrome -and !$Edge) {\r\n        # Output an error message and exit the script if no browser is selected\r\n        Write-Host -Object \"[Error] You must select a checkbox for a browser whose cache you would like to clear.\"\r\n        exit 1\r\n    }\r\n\r\n    # Define a function to get the list of logged-in users\r\n    function Get-LoggedInUsers {\r\n        # Run the 'quser.exe' command to get the list of logged-in users\r\n        $quser = quser.exe\r\n        # Replace multiple spaces with a comma, then convert the output to CSV format\r\n        $quser -replace '\\s{2,}', ',' -replace '&gt;' | ConvertFrom-Csv\r\n    }\r\n\r\n    function Get-UserHives {\r\n        param (\r\n            [Parameter()]\r\n            [ValidateSet('AzureAD', 'DomainAndLocal', 'All')]\r\n            [String]$Type = \"All\",\r\n            [Parameter()]\r\n            [String[]]$ExcludedUsers,\r\n            [Parameter()]\r\n            [switch]$IncludeDefault\r\n        )\r\n    \r\n        # User account SIDs follow specific patterns depending on if they are Azure AD, Domain, or local accounts.\r\n        $Patterns = switch ($Type) {\r\n            \"AzureAD\" { \"S-1-12-1-(\\d+-?){4}$\" }\r\n            \"DomainAndLocal\" { \"S-1-5-21-(\\d+-?){4}$\" }\r\n            \"All\" { \"S-1-12-1-(\\d+-?){4}$\" ; \"S-1-5-21-(\\d+-?){4}$\" } \r\n        }\r\n    \r\n        # Retrieve user profiles by matching account SIDs to the defined patterns.\r\n        $UserProfiles = Foreach ($Pattern in $Patterns) { \r\n            Get-ItemProperty \"HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\*\" |\r\n                Where-Object { $_.PSChildName -match $Pattern } | \r\n                Select-Object @{Name = \"SID\"; Expression = { $_.PSChildName } },\r\n                @{Name = \"UserName\"; Expression = { \"$($_.ProfileImagePath | Split-Path -Leaf)\" } }, \r\n                @{Name = \"UserHive\"; Expression = { \"$($_.ProfileImagePath)\\NTuser.dat\" } }, \r\n                @{Name = \"Path\"; Expression = { $_.ProfileImagePath } }\r\n        }\r\n    \r\n        # Optionally include the .Default user profile if requested.\r\n        switch ($IncludeDefault) {\r\n            $True {\r\n                $DefaultProfile = \"\" | Select-Object UserName, SID, UserHive, Path\r\n                $DefaultProfile.UserName = \"Default\"\r\n                $DefaultProfile.SID = \"DefaultProfile\"\r\n                $DefaultProfile.Userhive = \"$env:SystemDrive\\Users\\Default\\NTUSER.DAT\"\r\n                $DefaultProfile.Path = \"C:\\Users\\Default\"\r\n\r\n                # Add default profile to the list if it's not in the excluded users list\r\n                $DefaultProfile | Where-Object { $ExcludedUsers -notcontains $_.UserName }\r\n            }\r\n        }\r\n\r\n        # Filter out the excluded users from the user profiles list and return the result.\r\n        $UserProfiles | Where-Object { $ExcludedUsers -notcontains $_.UserName }\r\n    }\r\n    \r\n    # Function to find installation keys based on the display name\r\n    function Find-InstallKey {\r\n        [CmdletBinding()]\r\n        param (\r\n            [Parameter(ValueFromPipeline = $True)]\r\n            [String]$DisplayName,\r\n            [Parameter()]\r\n            [Switch]$UninstallString,\r\n            [Parameter()]\r\n            [String]$UserBaseKey\r\n        )\r\n        process {\r\n            # Initialize an empty list to hold installation objects\r\n            $InstallList = New-Object System.Collections.Generic.List[Object]\r\n            \r\n            # Search for programs in 32-bit and 64-bit system locations. Then add them to the list if they match the display name\r\n            $Result = Get-ChildItem -Path \"Registry::HKEY_LOCAL_MACHINE\\Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*\" | Get-ItemProperty | Where-Object { $_.DisplayName -like \"*$DisplayName*\" }\r\n            if ($Result) { $InstallList.Add($Result) }\r\n\r\n            $Result = Get-ChildItem -Path \"Registry::HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*\" | Get-ItemProperty | Where-Object { $_.DisplayName -like \"*$DisplayName*\" }\r\n            if ($Result) { $InstallList.Add($Result) }\r\n\r\n            # If a user base key is specified, search in the user-specified 64-bit and 32-bit paths.\r\n            if ($UserBaseKey) {\r\n                $Result = Get-ChildItem -Path \"$UserBaseKey\\Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*\" | Get-ItemProperty | Where-Object { $_.DisplayName -like \"*$DisplayName*\" }\r\n                if ($Result) { $InstallList.Add($Result) }\r\n    \r\n                $Result = Get-ChildItem -Path \"$UserBaseKey\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*\" | Get-ItemProperty | Where-Object { $_.DisplayName -like \"*$DisplayName*\" }\r\n                if ($Result) { $InstallList.Add($Result) }\r\n            }\r\n    \r\n            # If the UninstallString switch is specified, return only the uninstall strings; otherwise, return the full installation objects.\r\n            if ($UninstallString) {\r\n                $InstallList | Select-Object -ExpandProperty UninstallString -ErrorAction SilentlyContinue\r\n            }\r\n            else {\r\n                $InstallList\r\n            }\r\n        }\r\n    }\r\n\r\n    function Test-IsSystem {\r\n        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()\r\n        return $id.Name -like \"NT AUTHORITY*\" -or $id.IsSystem\r\n    }\r\n\r\n    if (!$ExitCode) {\r\n        $ExitCode = 0\r\n    }\r\n}\r\nprocess {\r\n    # Initialize a list to store users whose cache needs to be cleared\r\n    $UsersToClear = New-Object System.Collections.Generic.List[object]\r\n\r\n    # Get all user profiles\r\n    $AllUserProfiles = Get-UserHives\r\n\r\n    # If specific usernames are provided\r\n    if ($Usernames) {\r\n        $Usernames -split \",\" | ForEach-Object {\r\n            $User = $_.Trim()\r\n\r\n            # Check if different user to existing user\r\n            if (!(Test-IsSystem) -and $User -ne $env:username) {\r\n                Write-Host -Object \"[Error] Unable to clear cache for $User.\"\r\n                Write-Host -Object \"[Error] Please run as 'System' to clear the cache for users other than the currently logged-on user.\"\r\n                $ExitCode = 1\r\n                return\r\n            }\r\n\r\n            # Ensure username does not contain illegal characters.\r\n            if ($_.Trim() -match '\\[|\\]|:|;|\\||=|\\+|\\*|\\?|&lt;|&gt;|\/|\\\\|\"|@') {\r\n                Write-Host -Object (\"[Error] '$User' contains one of the following invalid characters.\" + ' \" [ ] : ; | = + * ? &lt; &gt; \/ \\ @')\r\n                $ExitCode = 1\r\n                return\r\n            }\r\n\r\n            # Ensure the username does not contain spaces.\r\n            if ($User -match '\\s') {\r\n                Write-Host -Object (\"[Error] '$User' is an invalid username because it contains a space.\")\r\n                $ExitCode = 1\r\n                return\r\n            }\r\n\r\n            # Ensure the username is not longer than 20 characters.\r\n            $UserNameCharacters = $User | Measure-Object -Character | Select-Object -ExpandProperty Characters\r\n            if ($UserNameCharacters -gt 20) {\r\n                Write-Host -Object \"[Error] '$($_.Trim())' is an invalid username because it is too long. The username needs to be less than or equal to 20 characters.\"\r\n                $ExitCode = 1\r\n                return\r\n            }\r\n\r\n            # Check if the user exists in the user profiles.\r\n            if ($($AllUserProfiles.Username) -notcontains $User) {\r\n                Write-Host \"[Error] User '$User' either does not exist or has not signed in yet. Please see the table below for initialized profiles.\"\r\n                $AllUserProfiles | Format-Table Username, Path | Out-String | Write-Host\r\n                $ExitCode = 1\r\n                return\r\n            }\r\n\r\n            # Add the user profile to the list of users to clear.\r\n            $UsersToClear.Add(( $AllUserProfiles | Where-Object { $_.Username -eq $User }  ))\r\n        }\r\n\r\n        # Check if no valid usernames were given.\r\n        if ($UsersToClear.Count -eq 0) { \r\n            Write-Host -Object \"[Error] No valid username was given.\"\r\n            exit 1\r\n        }\r\n    }\r\n    elseif (Test-IsSystem) {\r\n        # If running as System, add all user profiles to the list\r\n        $AllUserProfiles | ForEach-Object {\r\n            $UsersToClear.Add($_)\r\n        }\r\n    }\r\n    else {\r\n        # Otherwise, add the currently logged-in user to the list\r\n        $UsersToClear.Add(( $AllUserProfiles | Where-Object { $_.Username -eq $env:USERNAME } ))\r\n    }\r\n\r\n    $LoadedProfiles = New-Object System.Collections.Generic.List[string]\r\n\r\n    # Iterate over each user in the list of users to clear\r\n    $UsersToClear | ForEach-Object {\r\n        # Load the user's registry hive (ntuser.dat) if it's not already loaded\r\n        if ((Test-Path Registry::HKEY_USERS\\$($_.SID)) -eq $false) {\r\n            $LoadedProfiles.Add(\"$($_.SID)\")\r\n\r\n            Start-Process -FilePath \"cmd.exe\" -ArgumentList \"\/C reg.exe LOAD HKU\\$($_.SID) `\"$($_.UserHive)`\"\" -Wait -WindowStyle Hidden\r\n        }\r\n\r\n        # Find the Firefox installation for the user\r\n        if ($Firefox) {\r\n            $FirefoxInstallation = Find-InstallKey -DisplayName \"Mozilla Firefox\" -UserBaseKey \"Registry::HKEY_USERS\\$($_.SID)\"\r\n        }\r\n\r\n        # Find the Chrome installation for the user\r\n        if ($Chrome) {\r\n            $ChromeInstallation = Find-InstallKey -DisplayName \"Google Chrome\" -UserBaseKey \"Registry::HKEY_USERS\\$($_.SID)\"\r\n        }\r\n\r\n        # Find the Edge installation for the user\r\n        if ($Edge) {\r\n            $EdgeInstallation = Find-InstallKey -DisplayName \"Microsoft Edge\" -UserBaseKey \"Registry::HKEY_USERS\\$($_.SID)\"\r\n        }\r\n    }\r\n\r\n    # If force closing browsers is requested\r\n    if ($ForceCloseBrowsers) {\r\n        # Check and handle running Firefox processes\r\n        if ($Firefox -and (Get-Process -Name \"firefox\" -ErrorAction SilentlyContinue)) {\r\n            Write-Warning -Message \"Running Mozilla Firefox processess detected.\"\r\n            $FirefoxProcesses = Get-Process -Name \"firefox\" -ErrorAction SilentlyContinue\r\n        }\r\n\r\n        # Check and handle running Chrome processes\r\n        if ($Chrome -and (Get-Process -Name \"chrome\" -ErrorAction SilentlyContinue)) {\r\n            Write-Warning -Message \"Running Google Chrome processess detected.\"\r\n            $ChromeProcesses = Get-Process -Name \"chrome\" -ErrorAction SilentlyContinue\r\n        }\r\n\r\n        # Check and handle running Edge processes\r\n        if ($Edge -and (Get-Process -Name \"msedge\" -ErrorAction SilentlyContinue)) {\r\n            Write-Warning -Message \"Running Microsoft Edge processess detected.\"\r\n            $EdgeProcesses = Get-Process -Name \"msedge\" -ErrorAction SilentlyContinue\r\n        }\r\n    }\r\n\r\n    # Iterate over each user in the list of users to clear\r\n    $UsersToClear | ForEach-Object {\r\n        Write-Host -Object \"`nClearing browser cache for $($_.Username)\"\r\n\r\n        # Handle Firefox cache clearing\r\n        if ($Firefox -and !$FirefoxInstallation) {\r\n            Write-Warning -Message \"Mozilla Firefox is not installed!\"\r\n        }\r\n        elseif ($Firefox) {\r\n            if (Test-Path -Path \"$($_.Path)\\AppData\\Local\\Mozilla\\Firefox\\Profiles\") {\r\n\r\n                if ($ForceCloseBrowsers -and $FirefoxProcesses) {\r\n                    Write-Host -Object \"Closing Mozilla Firefox processes for $($_.Username) as requested.\"\r\n\r\n                    $User = $_.Username\r\n                    $RelevantAccount = Get-LoggedInUsers | Where-Object { $User -match $_.USERNAME }\r\n                    $RelevantProcess = $FirefoxProcesses | Where-Object { $RelevantAccount.ID -contains $_.SI }\r\n\r\n                    try {\r\n                        $RelevantProcess | ForEach-Object { $_ | Stop-Process -Force -ErrorAction Stop }\r\n                    }\r\n                    catch {\r\n                        Write-Host -Object \"[Error] Failed to close one of Mozilla Firefox's processes.\"\r\n                        Write-Host -Object \"[Error] $($_.Exception.Message)\"\r\n                        $ExitCode = 1\r\n                    }\r\n                }\r\n\r\n                Write-Host -Object \"Clearing Mozilla Firefox's browser cache for $($_.Username).\"\r\n\r\n                try {\r\n                    Get-ChildItem -Path \"$($_.Path)\\AppData\\Local\\Mozilla\\Firefox\\Profiles\\*\\cache2\" -Recurse -Force -ErrorAction SilentlyContinue | Where-Object { $_.PSIsContainer -eq $False } | Remove-Item -ErrorAction Stop\r\n                }\r\n                catch {\r\n                    Write-Host -Object \"[Error] Unable to clear Mozilla Firefox's cache.\"\r\n                    Write-Host -Object \"[Error] $($_.Exception.Message)\"\r\n                    $ExitCode = 1\r\n                }\r\n            }\r\n            else {\r\n                Write-Host -Object \"[Error] Mozilla Firefox's local appdata folder is not at '$($_.Path)\\AppData\\Local\\Mozilla\\Firefox\\Profiles'. Unable to clear cache.\"\r\n                $ExitCode = 1\r\n            }\r\n        }\r\n\r\n        # Handle Chrome cache clearing\r\n        if ($Chrome -and !$ChromeInstallation) {\r\n            Write-Warning -Message \"Google Chrome is not installed!\"\r\n        }\r\n        elseif ($Chrome) {\r\n            if (Test-Path -Path \"$($_.Path)\\AppData\\Local\\Google\") {\r\n\r\n                if ($ForceCloseBrowsers -and $ChromeProcesses) {\r\n                    Write-Host -Object \"Closing Google Chrome processes for $($_.Username) as requested.\"\r\n\r\n                    $User = $_.Username\r\n                    $RelevantAccount = Get-LoggedInUsers | Where-Object { $User -match $_.USERNAME }\r\n                    $RelevantProcess = $ChromeProcesses | Where-Object { $RelevantAccount.ID -contains $_.SI }\r\n\r\n                    try {\r\n                        $RelevantProcess | ForEach-Object { $_ | Stop-Process -Force -ErrorAction Stop }\r\n                    }\r\n                    catch {\r\n                        Write-Host -Object \"[Error] Failed to close one of Google Chrome's processes.\"\r\n                        Write-Host -Object \"[Error] $($_.Exception.Message)\"\r\n                        $ExitCode = 1\r\n                    }\r\n                }\r\n\r\n                Write-Host -Object \"Clearing Google Chrome's browser cache for $($_.Username).\"\r\n\r\n                try{\r\n                    Get-ChildItem -Path \"$($_.Path)\\AppData\\Local\\Google\\Chrome\\User Data\\*\\Cache\" -Recurse -Force -ErrorAction SilentlyContinue | Where-Object { $_.PSIsContainer -eq $False } | Remove-Item -ErrorAction Stop\r\n                    Get-ChildItem -Path \"$($_.Path)\\AppData\\Local\\Google\\Chrome\\User Data\\*\\Code Cache\" -Recurse -Force -ErrorAction SilentlyContinue | Where-Object { $_.PSIsContainer -eq $False } | Remove-Item -ErrorAction Stop\r\n                    Get-ChildItem -Path \"$($_.Path)\\AppData\\Local\\Google\\Chrome\\User Data\\*\\GPUCache\" -Recurse -Force -ErrorAction SilentlyContinue | Where-Object { $_.PSIsContainer -eq $False } | Remove-Item -ErrorAction Stop\r\n                }catch{\r\n                    Write-Host -Object \"[Error] Unable to clear Google Chrome's cache.\"\r\n                    Write-Host -Object \"[Error] $($_.Exception.Message)\"\r\n                    $ExitCode = 1\r\n                }\r\n            }else {\r\n                Write-Host -Object \"[Error] Chrome's local appdata folder is not at '$($_.Path)\\AppData\\Local\\Google'. Unable to clear cache.\"\r\n                $ExitCode = 1\r\n            }\r\n        }\r\n\r\n        # Handle Edge cache clearing\r\n        if ($Edge -and !$EdgeInstallation) {\r\n            Write-Warning -Message \"Microsoft Edge is not installed!\"\r\n        }\r\n        elseif ($Edge) {\r\n            if (Test-Path -Path \"$($_.Path)\\AppData\\Local\\Microsoft\\Edge\") {\r\n                if ($ForceCloseBrowsers -and $ChromeProcesses) {\r\n                    Write-Host -Object \"Closing Microsoft Edge processes for $($_.Username) as requested.\"\r\n                    \r\n                    $User = $_.Username\r\n                    $RelevantAccount = Get-LoggedInUsers | Where-Object { $User -match $_.USERNAME }\r\n                    $RelevantProcess = $EdgeProcesses | Where-Object { $RelevantAccount.ID -contains $_.SI }\r\n\r\n                    try {\r\n                        $RelevantProcess | ForEach-Object { $_ | Stop-Process -Force -ErrorAction Stop }\r\n                    }\r\n                    catch {\r\n                        Write-Host -Object \"[Error] Failed to close one of Microsoft Edge's processes.\"\r\n                        Write-Host -Object \"[Error] $($_.Exception.Message)\"\r\n                        $ExitCode = 1\r\n                    }\r\n                }\r\n\r\n                Write-Host -Object \"Clearing Microsoft Edge's browser cache for $($_.Username).\"\r\n\r\n                try{\r\n                    Get-ChildItem -Path \"$($_.Path)\\AppData\\Local\\Microsoft\\Edge\\User Data\\*\\Cache\" -Recurse -Force -ErrorAction SilentlyContinue | Where-Object { $_.PSIsContainer -eq $False } | Remove-Item -ErrorAction Stop\r\n                    Get-ChildItem -Path \"$($_.Path)\\AppData\\Local\\Microsoft\\Edge\\User Data\\*\\Code Cache\" -Recurse -Force -ErrorAction SilentlyContinue | Where-Object { $_.PSIsContainer -eq $False } | Remove-Item -ErrorAction Stop\r\n                    Get-ChildItem -Path \"$($_.Path)\\AppData\\Local\\Microsoft\\Edge\\User Data\\*\\GPUCache\" -Recurse -Force -ErrorAction SilentlyContinue | Where-Object { $_.PSIsContainer -eq $False } | Remove-Item -ErrorAction Stop\r\n                }catch{\r\n                    Write-Host -Object \"[Error] Unable to clear Microsoft Edge's cache.\"\r\n                    Write-Host -Object \"[Error] $($_.Exception.Message)\"\r\n                    $ExitCode = 1\r\n                }\r\n            }\r\n            else {\r\n                Write-Host -Object \"[Error] Microsoft Edge's local appdata folder is not at '$($_.Path)\\AppData\\Local\\Microsoft\\Edge'. Unable to clear cache.\"\r\n                $ExitCode = 1\r\n            }\r\n        }\r\n\r\n        Write-Host \"\"\r\n    }\r\n\r\n    # Iterate over each loaded profile\r\n    Foreach ($LoadedProfile in $LoadedProfiles) {\r\n        [gc]::Collect()\r\n        Start-Sleep -Seconds 1\r\n        Start-Process -FilePath \"cmd.exe\" -ArgumentList \"\/C reg.exe UNLOAD HKU\\$($LoadedProfile)\" -Wait -WindowStyle Hidden | Out-Null\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\"><p>Risparmia tempo con gli oltre 300 script del Dojo NinjaOne.<\/p>\n<p>\u2192 <a class=\"waffle-rich-text-link\" href=\"https:\/\/www.ninjaone.com\/it\/prova-gratuita\/\">Accedi oggi stesso<\/a>.<\/p>\n<\/div>\n<h2>Analisi dettagliata delle sezioni dello script <span data-contrast=\"none\">per cancellare la cache del browser<\/span><\/h2>\n<h3>1. Parametri e inizializzazione<\/h3>\n<p><span data-contrast=\"none\">Lo script per cancellare la cache del browser inizia definendo i parametri per specificare i browser di destinazione (-Firefox, -Chrome, -Edge), gli utenti di destinazione (-Usernames) e se chiudere forzatamente i browser (-ForceCloseBrowsers). Le variabili ambientali predefinite consentono una configurazione dinamica per gli scenari di automazione.<\/span><span data-ccp-props=\"{&quot;134233117&quot;:false,&quot;134233118&quot;:false,&quot;335559738&quot;:240,&quot;335559739&quot;:240}\">\u00a0<\/span><\/p>\n<h3>2. Convalida e gestione degli errori<\/h3>\n<p><span data-contrast=\"none\">Prima di procedere, lo script per cancellare la cache del browser controlla se \u00e8 stato selezionato un browser per procedere con la cancellazione della cache. In caso contrario, viene generato un errore e lo script termina. Allo stesso modo, convalida gli input degli utenti, assicurandosi che i nomi utente siano formattati correttamente e corrispondano ai profili esistenti.<\/span><span data-ccp-props=\"{&quot;134233117&quot;:false,&quot;134233118&quot;:false,&quot;335559738&quot;:240,&quot;335559739&quot;:240}\">\u00a0<\/span><\/p>\n<h3>3. Rilevamento del profilo utente<\/h3>\n<p><span data-contrast=\"none\">Utilizzando funzioni come Get-UserHives e Get-LoggedInUsers, lo script identifica i profili degli utenti connessi o quelli specificati dal parametro -Usernames. Questi profili vengono confrontati con il registro locale per individuare le installazioni del browser specifiche dell&#8217;utente.<\/span><span data-ccp-props=\"{&quot;134233117&quot;:false,&quot;134233118&quot;:false,&quot;335559738&quot;:240,&quot;335559739&quot;:240}\">\u00a0<\/span><\/p>\n<h3>4. Cancellazione della cache del browser<\/h3>\n<p><span data-contrast=\"none\">A seconda dei browser specificati, lo script naviga nelle directory della cache pertinenti:<\/span><span data-ccp-props=\"{&quot;134233117&quot;:false,&quot;134233118&quot;:false,&quot;335559738&quot;:240,&quot;335559739&quot;:240}\">\u00a0<\/span><\/p>\n<p><strong><span data-contrast=\"none\">a. Firefox<\/span><\/strong><span data-contrast=\"none\">: Cancella i file nella cartella AppData\\Local\\Mozilla\\Firefox\\Profiles\\*\\cache2.<\/span><span data-ccp-props=\"{&quot;134233117&quot;:false,&quot;134233118&quot;:false,&quot;335559738&quot;:0,&quot;335559739&quot;:0}\">\u00a0<\/span><\/p>\n<p><strong><span data-contrast=\"none\">b. Chrome<\/span><\/strong><span data-contrast=\"none\">: Agisce su AppData\\Local\\Google\\Chrome\\User Data\\*\\Cache, Code Cache, and GPUCache.<\/span><span data-ccp-props=\"{&quot;134233117&quot;:false,&quot;134233118&quot;:false,&quot;335559738&quot;:0,&quot;335559739&quot;:0}\">\u00a0<\/span><\/p>\n<p><strong><span data-contrast=\"none\">c. Edge<\/span><\/strong><span data-contrast=\"none\">: Cancella i dati delle directory contenute in AppData\\Local\\Microsoft\\Edge.<\/span><span data-ccp-props=\"{&quot;134233117&quot;:false,&quot;134233118&quot;:false,&quot;335559738&quot;:0,&quot;335559739&quot;:0}\">\u00a0<\/span><\/p>\n<p><span data-contrast=\"none\">Se si usa -ForceCloseBrowsers, lo script interrompe i processi attivi del browser prima di cancellare la cache, per evitare conflitti durante l&#8217;operazione.<\/span><span data-ccp-props=\"{&quot;134233117&quot;:false,&quot;134233118&quot;:false,&quot;335559738&quot;:240,&quot;335559739&quot;:240}\">\u00a0<\/span><\/p>\n<h3>5. Gestione del registro<\/h3>\n<p><span data-contrast=\"none\">Lo script per cancellare la cache del browser carica e scarica dinamicamente gli hives di registro specifici dell&#8217;utente (ntuser.dat) per accedere alle impostazioni del browser. Questo passaggio \u00e8 fondamentale per le operazioni che coinvolgono utenti che non hanno ancora effettuato il login.<\/span><span data-ccp-props=\"{&quot;134233117&quot;:false,&quot;134233118&quot;:false,&quot;335559738&quot;:240,&quot;335559739&quot;:240}\">\u00a0<\/span><\/p>\n<h3>6. Gestione del codice di uscita<\/h3>\n<p><span data-contrast=\"none\">Per consentire l&#8217;integrazione con i flussi di lavoro automatizzati, lo script per cancellare la cache del browser imposta i codici di uscita in base al successo o agli errori riscontrati durante l&#8217;esecuzione.<\/span><span data-ccp-props=\"{&quot;134233117&quot;:false,&quot;134233118&quot;:false,&quot;335559738&quot;:240,&quot;335559739&quot;:240}\">\u00a0<\/span><span data-ccp-props=\"{}\">\u00a0<\/span><\/p>\n<h2>Applicazione concreta<\/h2>\n<p><strong><span data-contrast=\"none\">Scenario<\/span><\/strong><span data-contrast=\"none\">: Il team IT di un&#8217;azienda nota problemi di prestazioni nei dispositivi dei dipendenti a causa di un eccesso di dati nella cache dei browser. Il team utilizza questo script per cancellare le cache del browser di tutti gli utenti durante il fine settimana senza interrompere i flussi di lavoro.<\/span><span data-ccp-props=\"{&quot;134233117&quot;:false,&quot;134233118&quot;:false,&quot;335559738&quot;:240,&quot;335559739&quot;:240}\">\u00a0<\/span><\/p>\n<h3>Metodi a confronto per cancellare la cache del browser<\/h3>\n<ol>\n<li><strong><span data-contrast=\"none\">Cancellazione manuale<\/span><\/strong><span data-contrast=\"none\">: Gli utenti possono eliminare manualmente i file della cache tramite le impostazioni del browser: un processo lento e ripetitivo, soggetto a errori umani.<\/span><span data-ccp-props=\"{&quot;134233117&quot;:false,&quot;134233118&quot;:false,&quot;335559738&quot;:0,&quot;335559739&quot;:0}\">\u00a0<\/span><\/li>\n<li><strong><span data-contrast=\"none\">Oggetti dei criteri di gruppo (GPO)<\/span><\/strong><span data-contrast=\"none\">: Questo metodo offre un controllo centralizzato, ma manca di granularit\u00e0 per utenti o browser specifici.<\/span><span data-ccp-props=\"{&quot;134233117&quot;:false,&quot;134233118&quot;:false,&quot;335559738&quot;:0,&quot;335559739&quot;:0}\">\u00a0<\/span><\/li>\n<li><strong><span data-contrast=\"none\">Strumenti di terze parti<\/span><\/strong><span data-contrast=\"none\">: Pur essendo efficaci, questi strumenti hanno spesso un costo e possono mancare della flessibilit\u00e0 di uno script personalizzato.<\/span><span data-ccp-props=\"{&quot;134233117&quot;:false,&quot;134233118&quot;:false,&quot;335559738&quot;:0,&quot;335559739&quot;:0}\">\u00a0<\/span><\/li>\n<\/ol>\n<p><span data-contrast=\"none\">Questo script \u00e8 in grado di garantire un equilibrio tra automazione, granularit\u00e0 ed efficienza dei costi, e rappresenta quindi la scelta ideale per i team IT.<\/span><span data-ccp-props=\"{&quot;134233117&quot;:false,&quot;134233118&quot;:false,&quot;335559738&quot;:240,&quot;335559739&quot;:240}\">\u00a0<\/span><\/p>\n<h2>Domande frequenti<\/h2>\n<ol>\n<li><strong><span data-contrast=\"none\">Posso utilizzare questo script per cancellare la cache del browser su Windows Server?<\/span><\/strong><br \/>\n<span data-contrast=\"none\">S\u00ec, lo script per cancellare la cache del browser supporta Windows Server 2016 e versioni successive.<\/span><span data-ccp-props=\"{&quot;134233117&quot;:false,&quot;134233118&quot;:false,&quot;335559738&quot;:240,&quot;335559739&quot;:240}\">\u00a0<\/span><\/li>\n<li><strong><span data-contrast=\"none\">Supporta altri browser?<\/span><\/strong><br \/>\n<span data-contrast=\"none\">Attualmente lo script pu\u00f2 essere usato con Firefox, Chrome ed Edge. Le personalizzazioni possono aggiungere il supporto per altri browser.<\/span><span data-ccp-props=\"{&quot;134233117&quot;:false,&quot;134233118&quot;:false,&quot;335559738&quot;:240,&quot;335559739&quot;:240}\">\u00a0<\/span><\/li>\n<li><strong><span data-contrast=\"none\">Cosa succede se manca la directory della cache?<\/span><\/strong><br \/>\n<span data-contrast=\"none\">Lo script per cancellare la cache del browser registra un errore ma continua l&#8217;esecuzione per altri utenti o browser.<\/span><span data-ccp-props=\"{&quot;134233117&quot;:false,&quot;134233118&quot;:false,&quot;335559738&quot;:240,&quot;335559739&quot;:240}\">\u00a0<\/span><\/li>\n<li><strong><span data-contrast=\"none\">Questo script per cancellare la cache del browser pu\u00f2 essere eseguito su account non di amministratore?<\/span><\/strong><br \/>\n<span data-contrast=\"none\">Se lanciato da un account non amministrativo pu\u00f2 cancellare la cache per l&#8217;utente corrente, ma per cancellare altri profili utente sono necessari privilegi amministrativi.<\/span><span data-ccp-props=\"{&quot;134233117&quot;:false,&quot;134233118&quot;:false,&quot;335559738&quot;:240,&quot;335559739&quot;:240}\">\u00a0<\/span><\/li>\n<\/ol>\n<h2>Implicazioni per la sicurezza informatica<\/h2>\n<p><span data-contrast=\"none\">Cancellare la cache del browser aiuta a rimuovere i dati potenzialmente sensibili come le pagine web salvate, i cookie e le credenziali memorizzate nella cache. Per le organizzazioni che gestiscono informazioni sensibili, la cancellazione di routine della cache riduce il rischio di violazione dei dati.<\/span><span data-ccp-props=\"{&quot;134233117&quot;:false,&quot;134233118&quot;:false,&quot;335559738&quot;:240,&quot;335559739&quot;:240}\">\u00a0<\/span><\/p>\n<p><span data-contrast=\"none\">Inoltre, la rimozione dei file di cache obsoleti riduce la possibilit\u00e0 di corruzione del browser, garantendo prestazioni uniformi su tutti gli endpoint.<\/span><span data-ccp-props=\"{&quot;134233117&quot;:false,&quot;134233118&quot;:false,&quot;335559738&quot;:240,&quot;335559739&quot;:240}\">\u00a0<\/span><\/p>\n<h2>Best practice per l&#8217;utilizzo dello script<\/h2>\n<ol>\n<li><strong><span data-contrast=\"none\">Testa in ambiente protetto<\/span><\/strong><br \/>\n<span data-contrast=\"none\">Prima di distribuire lo script per cancellare la cache del browser in produzione, testalo in un ambiente controllato per identificare potenziali errori.<\/span><span data-ccp-props=\"{&quot;134233117&quot;:false,&quot;134233118&quot;:false,&quot;335559738&quot;:240,&quot;335559739&quot;:240}\">\u00a0<\/span><\/li>\n<li><strong><span data-contrast=\"none\">Pianifica una manutenzione regolare<\/span><\/strong><br \/>\n<span data-contrast=\"none\">Integra questo script per cancellare la cache del browser nei programmi di manutenzione per automatizzare la cancellazione della cache nei vari sistemi.<\/span><span data-ccp-props=\"{&quot;134233117&quot;:false,&quot;134233118&quot;:false,&quot;335559738&quot;:240,&quot;335559739&quot;:240}\">\u00a0<\/span><\/li>\n<li><strong><span data-contrast=\"none\">Monitora i codici di uscita<\/span><\/strong><br \/>\n<span data-contrast=\"none\">Utilizza i codici di uscita dello script per cancellare la cache del browser per tenere traccia degli errori e perfezionare i parametri di esecuzione.<\/span><span data-ccp-props=\"{&quot;134233117&quot;:false,&quot;134233118&quot;:false,&quot;335559738&quot;:240,&quot;335559739&quot;:240}\">\u00a0<\/span><\/li>\n<li><strong><span data-contrast=\"none\">Usalo in combinazione con altri script di manutenzione<\/span><\/strong><br \/>\n<span data-contrast=\"none\">Utilizza questo script per cancellare la cache del browser insieme ad attivit\u00e0 come la pulizia del disco e l&#8217;ottimizzazione del registro per una gestione completa dell&#8217;integrit\u00e0 del sistema.<\/span><span data-ccp-props=\"{&quot;134233117&quot;:false,&quot;134233118&quot;:false,&quot;335559738&quot;:240,&quot;335559739&quot;:240}\">\u00a0<\/span><\/li>\n<\/ol>\n<h2>Considerazioni finali<\/h2>\n<p><span data-contrast=\"none\">La gestione delle cache dei browser \u00e8 solo un aspetto della manutenzione dell&#8217;infrastruttura IT, ma ha un impatto significativo sulle prestazioni e sulla sicurezza. Sebbene questo script fornisca una soluzione affidabile e flessibile per cancellare la cache del browser, strumenti come NinjaOne possono migliorare questi sforzi centralizzando la gestione IT. Con NinjaOne, i team IT possono automatizzare gli script, monitorare i sistemi e semplificare la manutenzione degli endpoint, garantendo un ambiente digitale sicuro ed efficiente.<\/span><span data-ccp-props=\"{&quot;134233117&quot;:false,&quot;134233118&quot;:false,&quot;335559738&quot;:240,&quot;335559739&quot;:240}\">\u00a0<\/span><\/p>\n","protected":false},"author":35,"featured_media":0,"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":[4269],"class_list":["post-390644","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\/390644","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=390644"}],"wp:attachment":[{"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/media?parent=390644"}],"wp:term":[{"taxonomy":"script_hub_category","embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/operating_system?post=390644"},{"taxonomy":"use_cases","embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/use_cases?post=390644"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}