{"id":392390,"date":"2024-12-16T06:27:25","date_gmt":"2024-12-16T06:27:25","guid":{"rendered":"https:\/\/www.ninjaone.com\/?post_type=script_hub&#038;p=392390"},"modified":"2024-12-16T06:29:15","modified_gmt":"2024-12-16T06:29:15","slug":"effacer-le-cache-navigateur-avec-powershell","status":"publish","type":"script_hub","link":"https:\/\/www.ninjaone.com\/fr\/script-hub\/effacer-le-cache-navigateur-avec-powershell\/","title":{"rendered":"Guide complet pour effacer le cache du navigateur avec PowerShell\u00a0"},"content":{"rendered":"<p><span data-contrast=\"none\">Effacer le cache du navigateur est une t\u00e2che courante mais cruciale dans les environnements informatiques. Le cache permet d&rsquo;am\u00e9liorer l&rsquo;exp\u00e9rience de l&rsquo;utilisateur en stockant des fichiers temporaires, mais au fil du temps, il peut devenir encombrant, entra\u00eenant des probl\u00e8mes de stockage et des retards de performance. Pour les administrateurs informatiques, en particulier ceux qui g\u00e8rent plusieurs utilisateurs dans des environnements d&rsquo;entreprise, <strong>effacer manuellement les caches des navigateurs<\/strong> peut s&rsquo;av\u00e9rer peu pratique. C&rsquo;est l\u00e0 qu&rsquo;interviennent les scripts PowerShell, avec leur solution programmatique et \u00e9volutive.<\/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\">Le script ci-dessus montre comment les professionnels de l&rsquo;informatique peuvent g\u00e9rer efficacement les caches des navigateurs pour diff\u00e9rents utilisateurs dans les principaux navigateurs tels que Mozilla Firefox, Google Chrome et Microsoft Edge. Nous allons nous pencher sur ses m\u00e9canismes, ses cas d&rsquo;utilisation et les bonnes pratiques.<\/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>Comprendre le script et son importance<\/h2>\n<p><span data-contrast=\"none\">Ce script est un outil polyvalent permettant d&rsquo;effacer les caches des navigateurs sur les syst\u00e8mes Windows. Con\u00e7u pour \u00eatre flexible, il peut\u00a0:<\/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\">Effacer le cache pour tous les utilisateurs (lorsqu&rsquo;il est ex\u00e9cut\u00e9 avec les privil\u00e8ges du syst\u00e8me).<\/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\">Cibler des utilisateurs sp\u00e9cifiques en fonction de leur nom d&rsquo;utilisateur.<\/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\">G\u00e9rer le cache des diff\u00e9rents navigateurs, y compris Firefox, Chrome et 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\">Fermer de force les processus du navigateur s&rsquo;ils sont en cours d&rsquo;ex\u00e9cution.<\/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\">Pour les <a href=\"https:\/\/www.ninjaone.com\/fr\/quest-ce-quun-msp\">fournisseurs de services g\u00e9r\u00e9s (MSP)<\/a> et les administrateurs informatiques, cette capacit\u00e9 est inestimable. Elle rationalise la maintenance de routine, garantit des performances constantes du navigateur et peut m\u00eame att\u00e9nuer les risques de s\u00e9curit\u00e9 associ\u00e9s \u00e0 des donn\u00e9es mises en cache obsol\u00e8tes.<\/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>Le script\u00a0:<\/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>Gagnez du temps gr\u00e2ce \u00e0 plus de 300 scripts du Dojo NinjaOne.<\/p>\n<p>\u2192 <a class=\"waffle-rich-text-link\" href=\"https:\/\/www.ninjaone.com\/fr\/phase-de-test-gratuit\/\">Obtenir l&rsquo;acc\u00e8s<\/a><\/p>\n<\/div>\n<h2>Analyse du script, \u00e9tape par \u00e9tape<\/h2>\n<h3>1. Param\u00e8tres et initialisation<\/h3>\n<p><span data-contrast=\"none\">Le script commence par d\u00e9finir des param\u00e8tres pour sp\u00e9cifier les navigateurs cibles (-Firefox, -Chrome, -Edge), les utilisateurs cibles (-Usernames) et la fermeture forc\u00e9e ou non des navigateurs (-ForceCloseBrowsers). Les variables environnementales par d\u00e9faut permettent une configuration dynamique pour les sc\u00e9narios d&rsquo;automatisation.<\/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. Validation et traitement des erreurs<\/h3>\n<p><span data-contrast=\"none\">Avant de poursuivre, le script v\u00e9rifie si un navigateur est s\u00e9lectionn\u00e9 pour l&rsquo;effacement du cache. Si ce n&rsquo;est pas le cas, il affiche une erreur et quitte le syst\u00e8me. De m\u00eame, il valide les entr\u00e9es des utilisateurs, en s&rsquo;assurant que les noms d&rsquo;utilisateur sont correctement format\u00e9s et correspondent aux profils existants.<\/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. D\u00e9tection du profil de l&rsquo;utilisateur<\/h3>\n<p><span data-contrast=\"none\">\u00c0 l&rsquo;aide de fonctions telles que Get-UserHives et Get-LoggedInUsers, le script identifie les profils des utilisateurs connect\u00e9s ou ceux sp\u00e9cifi\u00e9s par le param\u00e8tre -Usernames. Il fait correspondre ces profils au registre local afin de localiser les installations de navigateurs sp\u00e9cifiques \u00e0 l&rsquo;utilisateur.<\/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. Nettoyage du cache du navigateur<\/h3>\n<p><span data-contrast=\"none\">En fonction des navigateurs sp\u00e9cifi\u00e9s, le script navigue vers les r\u00e9pertoires de cache appropri\u00e9s\u00a0:<\/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\">\u00a0: Efface les fichiers sous 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\">\u00a0: Cible AppData\\Local\\Google\\Chrome\\Donn\u00e9es utilisateur\\*Cache, Code Cache, et 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\">\u00a0: Efface les r\u00e9pertoires similaires sous 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\">Si l&rsquo;option -ForceCloseBrowsers est utilis\u00e9e, elle arr\u00eate les processus actifs du navigateur avant d&rsquo;effacer le cache, ce qui garantit l&rsquo;absence de conflits pendant l&rsquo;op\u00e9ration.<\/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. Gestion du registre<\/h3>\n<p><span data-contrast=\"none\">Le script charge et d\u00e9charge dynamiquement des ruches de registre sp\u00e9cifiques \u00e0 l&rsquo;utilisateur (ntuser.dat) pour acc\u00e9der aux param\u00e8tres du navigateur. Cette \u00e9tape est essentielle pour les op\u00e9rations impliquant des utilisateurs qui ne sont pas actuellement connect\u00e9s.<\/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. Traitement du code de sortie<\/h3>\n<p><span data-contrast=\"none\">Pour permettre l&rsquo;int\u00e9gration dans des flux de travail automatis\u00e9s, le script d\u00e9finit des codes de sortie en fonction des succ\u00e8s ou des erreurs rencontr\u00e9s lors de l&rsquo;ex\u00e9cution.<\/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>Application concr\u00e8tes<\/h2>\n<p><strong><span data-contrast=\"none\">Sc\u00e9nario<\/span><\/strong><span data-contrast=\"none\">\u00a0: L&rsquo;\u00e9quipe informatique d&rsquo;une entreprise constate des probl\u00e8mes de performance sur les appareils des employ\u00e9s en raison de la saturation des caches des navigateurs. L&rsquo;\u00e9quipe utilise ce script pour effacer les caches de tous les utilisateurs pendant le week-end sans perturber les flux de travail.<\/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>Comparaison des m\u00e9thodes d&rsquo;effacement du cache du navigateur<\/h3>\n<ol>\n<li><strong><span data-contrast=\"none\">Effacement manuel<\/span><\/strong><span data-contrast=\"none\">\u00a0: les utilisateurs suppriment manuellement les fichiers cache via les param\u00e8tres du navigateur\u00a0: un processus lent, r\u00e9p\u00e9titif et sujet \u00e0 l&rsquo;erreur humaine.<\/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\">Objets de strat\u00e9gie de groupe (GPO)<\/span><\/strong><span data-contrast=\"none\">\u00a0: permet un contr\u00f4le centralis\u00e9 mais manque de pr\u00e9cision pour des utilisateurs ou des navigateurs sp\u00e9cifiques.<\/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\">Outils tiers<\/span><\/strong><span data-contrast=\"none\">\u00a0: Bien qu&rsquo;efficaces, ces outils ont souvent un co\u00fbt et peuvent ne pas offrir la flexibilit\u00e9 d&rsquo;un script personnalis\u00e9.<\/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\">Ce script trouve le juste milieu entre l&rsquo;automatisation, la pr\u00e9cision et la rentabilit\u00e9, ce qui en fait un choix id\u00e9al pour les \u00e9quipes informatiques.<\/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>Questions fr\u00e9quentes<\/h2>\n<ol>\n<li><strong><span data-contrast=\"none\">Puis-je utiliser ce script sur Windows Server\u00a0?<\/span><\/strong><br \/>\n<span data-contrast=\"none\">Oui, le script prend en charge Windows Server 2016 et les versions ult\u00e9rieures.<\/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\">Prend-il en charge d&rsquo;autres navigateurs\u00a0?<\/span><\/strong><br \/>\n<span data-contrast=\"none\">Actuellement, le script cible Firefox, Chrome et Edge. Les personnalisations peuvent ajouter la prise en charge de navigateurs suppl\u00e9mentaires.<\/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\">Que se passe-t-il si le r\u00e9pertoire cache est manquant\u00a0?<\/span><\/strong><br \/>\n<span data-contrast=\"none\">Le script enregistre une erreur mais continue de s&rsquo;ex\u00e9cuter pour les autres utilisateurs ou navigateurs.<\/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\">Ce script peut-il \u00eatre ex\u00e9cut\u00e9 sur des comptes non administrateurs\u00a0?<\/span><\/strong><br \/>\n<span data-contrast=\"none\">Il peut effacer le cache de l&rsquo;utilisateur actuel, mais des privil\u00e8ges administratifs sont n\u00e9cessaires pour effacer les profils d&rsquo;autres utilisateurs.<\/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>Implications pour la s\u00e9curit\u00e9 informatique<\/h2>\n<p><span data-contrast=\"none\">Le nettoyage des caches du navigateur permet de supprimer les donn\u00e9es potentiellement sensibles telles que les pages web sauvegard\u00e9es, les cookies et les informations d&rsquo;identification mises en cache. Pour les entreprises qui traitent des informations sensibles, l&rsquo;effacement syst\u00e9matique du cache r\u00e9duit le risque d&rsquo;atteinte \u00e0 la protection des donn\u00e9es.<\/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\">De plus, la suppression des fichiers de cache p\u00e9rim\u00e9s r\u00e9duit le risque de corruption du navigateur, ce qui garantit des performances constantes sur tous les terminaux.<\/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>Bonnes pratiques d&rsquo;utilisation de ce script<\/h2>\n<ol>\n<li><strong><span data-contrast=\"none\">Tester en environnement contr\u00f4l\u00e9<\/span><\/strong><br \/>\n<span data-contrast=\"none\">Avant de d\u00e9ployer le script dans l&rsquo;environnement de production, testez-le dans un environnement contr\u00f4l\u00e9 afin d&rsquo;identifier les erreurs potentielles.<\/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\">Planifier un entretien r\u00e9gulier<\/span><\/strong><br \/>\n<span data-contrast=\"none\">Int\u00e9grez ce script dans les programmes de maintenance afin d&rsquo;automatiser l&rsquo;effacement du cache sur l&rsquo;ensemble des syst\u00e8mes.<\/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\">Surveiller les codes de sortie<\/span><\/strong><br \/>\n<span data-contrast=\"none\">Utilisez les codes de sortie du script pour surveiller les erreurs et affiner les param\u00e8tres d&rsquo;ex\u00e9cution.<\/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\">Associer \u00e0 d&rsquo;autres scripts de maintenance<\/span><\/strong><br \/>\n<span data-contrast=\"none\">Associez ce script \u00e0 des t\u00e2ches telles que le nettoyage du disque et l&rsquo;optimisation du registre pour une gestion compl\u00e8te de l&rsquo;\u00e9tat du syst\u00e8me.<\/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>Conclusion<\/h2>\n<p><span data-contrast=\"none\">La gestion des caches de navigateurs n&rsquo;est qu&rsquo;un aspect de la maintenance de l&rsquo;infrastructure informatique, mais elle a un impact significatif sur les performances et la s\u00e9curit\u00e9. Si ce script fournit une solution efficace et flexible, des outils comme NinjaOne peuvent renforcer ces efforts en centralisant la gestion informatique. Avec NinjaOne, les \u00e9quipes informatiques peuvent automatiser les scripts, surveiller les syst\u00e8mes et simplifier la maintenance des terminaux, garantissant ainsi un environnement num\u00e9rique s\u00e9curis\u00e9 et efficace.<\/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":[4281],"class_list":["post-392390","script_hub","type-script_hub","status-publish","hentry","script_hub_category-windows"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.ninjaone.com\/fr\/wp-json\/wp\/v2\/script_hub\/392390","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.ninjaone.com\/fr\/wp-json\/wp\/v2\/script_hub"}],"about":[{"href":"https:\/\/www.ninjaone.com\/fr\/wp-json\/wp\/v2\/types\/script_hub"}],"author":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/fr\/wp-json\/wp\/v2\/users\/35"}],"replies":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/fr\/wp-json\/wp\/v2\/comments?post=392390"}],"wp:attachment":[{"href":"https:\/\/www.ninjaone.com\/fr\/wp-json\/wp\/v2\/media?parent=392390"}],"wp:term":[{"taxonomy":"script_hub_category","embeddable":true,"href":"https:\/\/www.ninjaone.com\/fr\/wp-json\/wp\/v2\/operating_system?post=392390"},{"taxonomy":"use_cases","embeddable":true,"href":"https:\/\/www.ninjaone.com\/fr\/wp-json\/wp\/v2\/use_cases?post=392390"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}