{"id":353797,"date":"2024-09-30T13:45:11","date_gmt":"2024-09-30T13:45:11","guid":{"rendered":"https:\/\/www.ninjaone.com\/script-hub\/establecer-un-navegador-predeterminado\/"},"modified":"2024-10-13T19:02:59","modified_gmt":"2024-10-13T19:02:59","slug":"establecer-un-navegador-predeterminado","status":"publish","type":"script_hub","link":"https:\/\/www.ninjaone.com\/es\/script-hub\/establecer-un-navegador-predeterminado\/","title":{"rendered":"C\u00f3mo establecer un navegador predeterminado para todos los usuarios con PowerShell: gu\u00eda paso a paso"},"content":{"rendered":"<p>Gestionar el navegador predeterminado en varios perfiles de usuario de un sistema Windows puede ser una tarea desalentadora, especialmente en entornos empresariales en los que la coherencia y el cumplimiento son cruciales. Automatizar este proceso con un script <a href=\"https:\/\/www.ninjaone.com\/it-hub\/endpoint-management\/what-is-powershell\/\" target=\"_blank\" rel=\"noopener\">PowerShell<\/a> simplifica la tarea, garantizando que todos los usuarios del sistema tengan la misma experiencia de navegaci\u00f3n.<\/p>\n<p>Este post explorar\u00e1 un\u00a0<strong>script PowerShell dise\u00f1ado para establecer un navegador predeterminado para todos los usuarios<\/strong>\u00a0en un equipo Windows, proporcionando a los profesionales de TI y <a href=\"https:\/\/www.ninjaone.com\/es\/que-es-un-msp\/\" target=\"_blank\" rel=\"noopener\">proveedores de servicios gestionados (MSP)<\/a> una poderosa herramienta para mantener el control sobre sus entornos.<\/p>\n<h2>Contexto<\/h2>\n<p>En un entorno de TI, especialmente en empresas o MSP, es vital mantener una experiencia de usuario coherente. Si hay varios usuarios en un mismo equipo o en una red, configurar manualmente el navegador predeterminado de cada perfil puede resultar laborioso y propenso a errores. Un script de PowerShell que automatice el proceso de establecer un navegador predeterminado no s\u00f3lo ahorra tiempo, sino que tambi\u00e9n garantiza la uniformidad, que puede ser fundamental para el cumplimiento de las normativas y la asistencia a los usuarios.<\/p>\n<p>Este script espec\u00edfico es una versi\u00f3n modificada de un script de Danysys, dise\u00f1ado para cambiar el navegador predeterminado de todos los usuarios mediante la actualizaci\u00f3n de las claves del registro. Es un script altamente adaptable, compatible con navegadores populares como Mozilla Firefox, Google Chrome y Microsoft Edge. Utilizando este script para establecer un navegador predeterminado, los administradores de TI pueden asegurarse de que todos los usuarios tienen el navegador correcto configurado por defecto, independientemente del n\u00famero de perfiles o del estado del sistema.<\/p>\n<h2>El script <strong>para establecer un navegador predeterminado <\/strong><\/h2>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\">#Requires -Version 5.1\r\n\r\n&lt;#\r\n.SYNOPSIS\r\n    Sets the default browser for all users.\r\n.DESCRIPTION\r\n    Sets the default browser for all users.\r\n.EXAMPLE\r\n    -Browser \"Mozilla Firefox\" -RestartExplorer\r\n\r\n    Setting default browser of Mozilla Firefox for Administrator.\r\n    Setting \r\n    Registry::HKEY_USERS\\S-1-5-21-528047445-1317477324-4168425688-500\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice\\Hash changed from 2q7+uVxu0\/A= to FKcuHm4FMN4=\r\n    Registry::HKEY_USERS\\S-1-5-21-528047445-1317477324-4168425688-500\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice\\ProgId changed from ChromeHTML to FirefoxURL-308046B0AF4A39CB\r\n    Setting \r\n    Registry::HKEY_USERS\\S-1-5-21-528047445-1317477324-4168425688-500\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\https\\UserChoice\\Hash changed from zR3ANZC6jVI= to clMyDtJdxck=\r\n    Registry::HKEY_USERS\\S-1-5-21-528047445-1317477324-4168425688-500\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\https\\UserChoice\\ProgId changed from ChromeHTML to FirefoxURL-308046B0AF4A39CB\r\n    Setting \r\n    Registry::HKEY_USERS\\S-1-5-21-528047445-1317477324-4168425688-500\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\htm\\UserChoice\\Hash changed from IQfza9L6Tfw= to t8+HFkmUAd0=\r\n    Registry::HKEY_USERS\\S-1-5-21-528047445-1317477324-4168425688-500\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\htm\\UserChoice\\ProgId changed from ChromeHTML to FirefoxHTML-308046B0AF4A39CB\r\n    Registry::HKEY_USERS\\S-1-5-21-528047445-1317477324-4168425688-500\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.htm\\UserChoice\\Hash changed from IQfza9L6Tfw= to t8+HFkmUAd0=\r\n    Registry::HKEY_USERS\\S-1-5-21-528047445-1317477324-4168425688-500\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.htm\\UserChoice\\ProgId changed from ChromeHTML to FirefoxHTML-308046B0AF4A39CB\r\n    Setting \r\n    Registry::HKEY_USERS\\S-1-5-21-528047445-1317477324-4168425688-500\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\html\\UserChoice\\Hash changed from 7CcRlkLW3ik= to q0Eix6jwLFg=\r\n    Registry::HKEY_USERS\\S-1-5-21-528047445-1317477324-4168425688-500\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\html\\UserChoice\\ProgId changed from ChromeHTML to FirefoxHTML-308046B0AF4A39CB\r\n    Registry::HKEY_USERS\\S-1-5-21-528047445-1317477324-4168425688-500\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.html\\UserChoice\\Hash changed from 7CcRlkLW3ik= to q0Eix6jwLFg=\r\n    Registry::HKEY_USERS\\S-1-5-21-528047445-1317477324-4168425688-500\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.html\\UserChoice\\ProgId changed from ChromeHTML to FirefoxHTML-308046B0AF4A39CB\r\n    Setting \r\n    Registry::HKEY_USERS\\S-1-5-21-528047445-1317477324-4168425688-500\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\xhtml\\UserChoice\\Hash changed from IC7TXk1anlM= to y2gIOuiaLb0=\r\n    Registry::HKEY_USERS\\S-1-5-21-528047445-1317477324-4168425688-500\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\xhtml\\UserChoice\\ProgId changed from ChromeHTML to FirefoxHTML-308046B0AF4A39CB\r\n    Registry::HKEY_USERS\\S-1-5-21-528047445-1317477324-4168425688-500\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.xhtml\\UserChoice\\Hash changed from IC7TXk1anlM= to y2gIOuiaLb0=\r\n    Registry::HKEY_USERS\\S-1-5-21-528047445-1317477324-4168425688-500\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.xhtml\\UserChoice\\ProgId changed from ChromeHTML to FirefoxHTML-308046B0AF4A39CB\r\n    Restarting Explorer.exe\r\n\r\nPARAMETER: -Browser \"Mozilla Firefox\"\r\n    Set the default browser to either \"Mozilla Firefox\", \"Google Chrome\" or \"Microsoft Edge\".\r\n\r\nPARAMETER: -Restart Explorer\r\n    Restarts Explorer.exe so that the desktop icons for .html files refresh immediately.\r\n    \r\nLICENSE:\r\n    Modified version from: https:\/\/github.com\/DanysysTeam\/PS-SFTA\/blob\/22a32292e576afc976a1167d92b50741ef523066\/SFTA.ps1\r\n    This script incorporates the `Get-HexDateTime` and `Get-Hash` functions from Danysys, without which it would not be possible.\r\n    \r\n    LICENSE: https:\/\/github.com\/DanysysTeam\/PS-SFTA\/blob\/22a32292e576afc976a1167d92b50741ef523066\/SFTA.ps1\r\n    MIT License\r\n    \r\n    Copyright (c) 2022 Danysys. &lt;danysys.com&gt;\r\n\r\n    Permission is hereby granted, free of charge, to any person obtaining a copy\r\n    of this software and associated documentation files (the \"Software\"), to deal\r\n    in the Software without restriction, including without limitation the rights\r\n    to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n    copies of the Software, and to permit persons to whom the Software is\r\n    furnished to do so, subject to the following conditions:\r\n\r\n    The above copyright notice and this permission notice shall be included in all\r\n    copies or substantial portions of the Software.\r\n\r\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n    SOFTWARE.\r\n\r\n.OUTPUTS\r\n    None\r\n.NOTES\r\n    Minimum OS Architecture Supported: Windows 10+\r\n    Release Notes:\r\n    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]$Browser,\r\n    [Parameter()]\r\n    [Switch]$RestartExplorer = [System.Convert]::ToBoolean($env:restartExplorer)\r\n)\r\n\r\nbegin {\r\n    if ($env:browser -and $env:browser -notlike \"null\") {\r\n        $Browser = $env:browser\r\n    }\r\n\r\n    # If no browser is selected, terminate with an error message.\r\n    if (-not $Browser) {\r\n        Write-Host \"[Error] Please select at least one browser!\"\r\n        Exit 1\r\n    }\r\n\r\n    # Test if running as Administrator\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    # Test if running as System\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    function Get-HexDateTime {\r\n        # This function was created by DanySys at https:\/\/github.com\/DanysysTeam\/PS-SFTA\r\n        [OutputType([string])]\r\n    \r\n        $now = [DateTime]::Now\r\n        $dateTime = [DateTime]::New($now.Year, $now.Month, $now.Day, $now.Hour, $now.Minute, 0)\r\n        $fileTime = $dateTime.ToFileTime()\r\n        $hi = ($fileTime -shr 32)\r\n        $low = ($fileTime -band 0xFFFFFFFFL)\r\n        ($hi.ToString(\"X8\") + $low.ToString(\"X8\")).ToLower()\r\n    }\r\n\r\n    function Get-Hash {\r\n        # This function was created by DanySys at https:\/\/github.com\/DanysysTeam\/PS-SFTA\r\n        [CmdletBinding()]\r\n        param (\r\n            [Parameter( Position = 0, Mandatory = $True )]\r\n            [string]\r\n            $BaseInfo\r\n        )\r\n    \r\n        function local:Get-ShiftRight {\r\n            [CmdletBinding()]\r\n            param (\r\n                [Parameter( Position = 0, Mandatory = $true)]\r\n                [long] $iValue, \r\n                \r\n                [Parameter( Position = 1, Mandatory = $true)]\r\n                [int] $iCount \r\n            )\r\n        \r\n            if ($iValue -band 0x80000000) {\r\n                Write-Output (( $iValue -shr $iCount) -bxor 0xFFFF0000)\r\n            }\r\n            else {\r\n                Write-Output ($iValue -shr $iCount)\r\n            }\r\n        }\r\n    \r\n        function local:Get-Long {\r\n            [CmdletBinding()]\r\n            param (\r\n                [Parameter( Position = 0, Mandatory = $true)]\r\n                [byte[]] $Bytes,\r\n        \r\n                [Parameter( Position = 1)]\r\n                [int] $Index = 0\r\n            )\r\n        \r\n            Write-Output ([BitConverter]::ToInt32($Bytes, $Index))\r\n        }\r\n    \r\n        function local:Convert-Int32 {\r\n            param (\r\n                [Parameter( Position = 0, Mandatory = $true)]\r\n                [long] $Value\r\n            )\r\n        \r\n            [byte[]] $bytes = [BitConverter]::GetBytes($Value)\r\n            return [BitConverter]::ToInt32( $bytes, 0) \r\n        }\r\n    \r\n        [Byte[]] $bytesBaseInfo = [System.Text.Encoding]::Unicode.GetBytes($baseInfo) \r\n        $bytesBaseInfo += 0x00, 0x00  \r\n        \r\n        $MD5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider\r\n        [Byte[]] $bytesMD5 = $MD5.ComputeHash($bytesBaseInfo)\r\n        \r\n        $lengthBase = ($baseInfo.Length * 2) + 2 \r\n        $length = (($lengthBase -band 4) -le 1) + (Get-ShiftRight $lengthBase 2) - 1\r\n        $base64Hash = \"\"\r\n    \r\n        if ($length -gt 1) {\r\n        \r\n            $map = @{PDATA = 0; CACHE = 0; COUNTER = 0 ; INDEX = 0; MD51 = 0; MD52 = 0; OUTHASH1 = 0; OUTHASH2 = 0;\r\n                R0 = 0; R1 = @(0, 0); R2 = @(0, 0); R3 = 0; R4 = @(0, 0); R5 = @(0, 0); R6 = @(0, 0); R7 = @(0, 0)\r\n            }\r\n        \r\n            $map.CACHE = 0\r\n            $map.OUTHASH1 = 0\r\n            $map.PDATA = 0\r\n            $map.MD51 = (((Get-Long $bytesMD5) -bor 1) + 0x69FB0000L)\r\n            $map.MD52 = ((Get-Long $bytesMD5 4) -bor 1) + 0x13DB0000L\r\n            $map.INDEX = Get-ShiftRight ($length - 2) 1\r\n            $map.COUNTER = $map.INDEX + 1\r\n        \r\n            while ($map.COUNTER) {\r\n                $map.R0 = Convert-Int32 ((Get-Long $bytesBaseInfo $map.PDATA) + [long]$map.OUTHASH1)\r\n                $map.R1[0] = Convert-Int32 (Get-Long $bytesBaseInfo ($map.PDATA + 4))\r\n                $map.PDATA = $map.PDATA + 8\r\n                $map.R2[0] = Convert-Int32 (($map.R0 * ([long]$map.MD51)) - (0x10FA9605L * ((Get-ShiftRight $map.R0 16))))\r\n                $map.R2[1] = Convert-Int32 ((0x79F8A395L * ([long]$map.R2[0])) + (0x689B6B9FL * (Get-ShiftRight $map.R2[0] 16)))\r\n                $map.R3 = Convert-Int32 ((0xEA970001L * $map.R2[1]) - (0x3C101569L * (Get-ShiftRight $map.R2[1] 16) ))\r\n                $map.R4[0] = Convert-Int32 ($map.R3 + $map.R1[0])\r\n                $map.R5[0] = Convert-Int32 ($map.CACHE + $map.R3)\r\n                $map.R6[0] = Convert-Int32 (($map.R4[0] * [long]$map.MD52) - (0x3CE8EC25L * (Get-ShiftRight $map.R4[0] 16)))\r\n                $map.R6[1] = Convert-Int32 ((0x59C3AF2DL * $map.R6[0]) - (0x2232E0F1L * (Get-ShiftRight $map.R6[0] 16)))\r\n                $map.OUTHASH1 = Convert-Int32 ((0x1EC90001L * $map.R6[1]) + (0x35BD1EC9L * (Get-ShiftRight $map.R6[1] 16)))\r\n                $map.OUTHASH2 = Convert-Int32 ([long]$map.R5[0] + [long]$map.OUTHASH1)\r\n                $map.CACHE = ([long]$map.OUTHASH2)\r\n                $map.COUNTER = $map.COUNTER - 1\r\n            }\r\n    \r\n            [Byte[]] $outHash = @(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)\r\n            [byte[]] $buffer = [BitConverter]::GetBytes($map.OUTHASH1)\r\n            $buffer.CopyTo($outHash, 0)\r\n            $buffer = [BitConverter]::GetBytes($map.OUTHASH2)\r\n            $buffer.CopyTo($outHash, 4)\r\n        \r\n            $map = @{PDATA = 0; CACHE = 0; COUNTER = 0 ; INDEX = 0; MD51 = 0; MD52 = 0; OUTHASH1 = 0; OUTHASH2 = 0;\r\n                R0 = 0; R1 = @(0, 0); R2 = @(0, 0); R3 = 0; R4 = @(0, 0); R5 = @(0, 0); R6 = @(0, 0); R7 = @(0, 0)\r\n            }\r\n        \r\n            $map.CACHE = 0\r\n            $map.OUTHASH1 = 0\r\n            $map.PDATA = 0\r\n            $map.MD51 = ((Get-Long $bytesMD5) -bor 1)\r\n            $map.MD52 = ((Get-Long $bytesMD5 4) -bor 1)\r\n            $map.INDEX = Get-ShiftRight ($length - 2) 1\r\n            $map.COUNTER = $map.INDEX + 1\r\n    \r\n            while ($map.COUNTER) {\r\n                $map.R0 = Convert-Int32 ((Get-Long $bytesBaseInfo $map.PDATA) + ([long]$map.OUTHASH1))\r\n                $map.PDATA = $map.PDATA + 8\r\n                $map.R1[0] = Convert-Int32 ($map.R0 * [long]$map.MD51)\r\n                $map.R1[1] = Convert-Int32 ((0xB1110000L * $map.R1[0]) - (0x30674EEFL * (Get-ShiftRight $map.R1[0] 16)))\r\n                $map.R2[0] = Convert-Int32 ((0x5B9F0000L * $map.R1[1]) - (0x78F7A461L * (Get-ShiftRight $map.R1[1] 16)))\r\n                $map.R2[1] = Convert-Int32 ((0x12CEB96DL * (Get-ShiftRight $map.R2[0] 16)) - (0x46930000L * $map.R2[0]))\r\n                $map.R3 = Convert-Int32 ((0x1D830000L * $map.R2[1]) + (0x257E1D83L * (Get-ShiftRight $map.R2[1] 16)))\r\n                $map.R4[0] = Convert-Int32 ([long]$map.MD52 * ([long]$map.R3 + (Get-Long $bytesBaseInfo ($map.PDATA - 4))))\r\n                $map.R4[1] = Convert-Int32 ((0x16F50000L * $map.R4[0]) - (0x5D8BE90BL * (Get-ShiftRight $map.R4[0] 16)))\r\n                $map.R5[0] = Convert-Int32 ((0x96FF0000L * $map.R4[1]) - (0x2C7C6901L * (Get-ShiftRight $map.R4[1] 16)))\r\n                $map.R5[1] = Convert-Int32 ((0x2B890000L * $map.R5[0]) + (0x7C932B89L * (Get-ShiftRight $map.R5[0] 16)))\r\n                $map.OUTHASH1 = Convert-Int32 ((0x9F690000L * $map.R5[1]) - (0x405B6097L * (Get-ShiftRight ($map.R5[1]) 16)))\r\n                $map.OUTHASH2 = Convert-Int32 ([long]$map.OUTHASH1 + $map.CACHE + $map.R3) \r\n                $map.CACHE = ([long]$map.OUTHASH2)\r\n                $map.COUNTER = $map.COUNTER - 1\r\n            }\r\n        \r\n            $buffer = [BitConverter]::GetBytes($map.OUTHASH1)\r\n            $buffer.CopyTo($outHash, 8)\r\n            $buffer = [BitConverter]::GetBytes($map.OUTHASH2)\r\n            $buffer.CopyTo($outHash, 12)\r\n        \r\n            [Byte[]] $outHashBase = @(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)\r\n            $hashValue1 = ((Get-Long $outHash 8) -bxor (Get-Long $outHash))\r\n            $hashValue2 = ((Get-Long $outHash 12) -bxor (Get-Long $outHash 4))\r\n        \r\n            $buffer = [BitConverter]::GetBytes($hashValue1)\r\n            $buffer.CopyTo($outHashBase, 0)\r\n            $buffer = [BitConverter]::GetBytes($hashValue2)\r\n            $buffer.CopyTo($outHashBase, 4)\r\n            $base64Hash = [Convert]::ToBase64String($outHashBase) \r\n        }\r\n    \r\n        $base64Hash\r\n    }\r\n\r\n    # Helper function for setting registry keys\r\n    function Set-RegKey {\r\n        param (\r\n            $Path,\r\n            $Name,\r\n            $Value,\r\n            [ValidateSet(\"DWord\", \"QWord\", \"String\", \"ExpandedString\", \"Binary\", \"MultiString\", \"Unknown\")]\r\n            $PropertyType = \"DWord\"\r\n        )\r\n        if (-not $(Test-Path -Path $Path)) {\r\n            # Check if path does not exist and create the path\r\n            New-Item -Path $Path -Force | Out-Null\r\n        }\r\n        if ((Get-ItemProperty -Path $Path -Name $Name -ErrorAction SilentlyContinue)) {\r\n            # Update property and print out what it was changed from and changed to\r\n            $CurrentValue = (Get-ItemProperty -Path $Path -Name $Name -ErrorAction SilentlyContinue).$Name\r\n            try {\r\n                Set-ItemProperty -Path $Path -Name $Name -Value $Value -Force -Confirm:$false -ErrorAction Stop | Out-Null\r\n            }\r\n            catch {\r\n                Write-Host \"[Error] Unable to set registry key for $Name at $Path please see below error!\"\r\n                Write-Host \"[Error] $($_.Exception.Message)\"\r\n                exit 1\r\n            }\r\n            Write-Host \"$Path\\$Name changed from $CurrentValue to $($(Get-ItemProperty -Path $Path -Name $Name -ErrorAction SilentlyContinue).$Name)\"\r\n        }\r\n        else {\r\n            # Create property with value\r\n            try {\r\n                New-ItemProperty -Path $Path -Name $Name -Value $Value -PropertyType $PropertyType -Force -Confirm:$false -ErrorAction Stop | Out-Null\r\n            }\r\n            catch {\r\n                Write-Host \"[Error] Unable to set registry key for $Name at $Path please see below error!\"\r\n                Write-Host \"[Error] $($_.Exception.Message)\"\r\n                exit 1\r\n            }\r\n            Write-Host \"Set $Path\\$Name to $($(Get-ItemProperty -Path $Path -Name $Name -ErrorAction SilentlyContinue).$Name)\"\r\n        }\r\n    }\r\n\r\n    # Retrieves all accounts on a system.\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 SID's follow a particular patter depending on if they're azure AD or a Domain account or a local \"workgroup\" account.\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        # We'll need the NTuser.dat file to load each users registry hive. So we grab it if their account sid matches the above pattern. \r\n        $UserProfiles = Foreach ($Pattern in $Patterns) { \r\n            Get-ItemProperty -Path \"Registry::HKEY_LOCAL_MACHINE\\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        # There are some situations where grabbing the .Default user's info is needed.\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                $DefaultProfile | Where-Object { $ExcludedUsers -notcontains $_.UserName }\r\n            }\r\n        }\r\n    \r\n        $UserProfiles | Where-Object { $ExcludedUsers -notcontains $_.UserName }\r\n    }\r\n\r\n    # This is used to check that the browser is installed.\r\n    function Find-UninstallKey {\r\n        [CmdletBinding()]\r\n        param (\r\n            [Parameter(ValueFromPipeline = $True)]\r\n            [String]$DisplayName,\r\n            [Parameter()]\r\n            [Switch]$UninstallString\r\n        )\r\n        process {\r\n            $UninstallList = New-Object System.Collections.Generic.List[Object]\r\n    \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) { $UninstallList.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) { $UninstallList.Add($Result) }\r\n    \r\n            # Programs don't always have an uninstall string listed here so to account for that I made this optional.\r\n            if ($UninstallString) {\r\n                $UninstallList | Select-Object -ExpandProperty UninstallString -ErrorAction SilentlyContinue\r\n            }\r\n            else {\r\n                $UninstallList\r\n            }\r\n        }\r\n    }\r\n}\r\nprocess {\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    # Protocols and file associations to set\r\n    $Protocols = \"http\", \"https\"\r\n    $Files = \"htm\", \"html\", \"xhtml\"\r\n\r\n    # Handlers for each product\r\n    switch ($Browser) {\r\n        \"Google Chrome\" {\r\n            $DisplayName = \"Chrome\"\r\n            $urlID = \"ChromeHTML\"\r\n            $htmlID = \"ChromeHTML\"\r\n        }\r\n        \"Microsoft Edge\" {\r\n            $DisplayName = \"Edge\"\r\n            $urlID = \"MSEdgeHTM\"\r\n            $htmlID = \"MSEdgeHTM\"\r\n        }\r\n        \"Mozilla Firefox\" {\r\n            $DisplayName = \"Firefox\"\r\n            $urlID = \"FirefoxURL-308046B0AF4A39CB\"\r\n            $htmlID = \"FirefoxHTML-308046B0AF4A39CB\"\r\n        }\r\n        default {\r\n            Write-Host \"[Error] Only the following browsers can be made the default. 'Google Chrome','Microsoft Edge' or 'Mozilla Firefox'.\"\r\n            exit 1\r\n        }\r\n    }\r\n\r\n    if (-not (Find-UninstallKey -DisplayName \"$DisplayName\")) {\r\n        Write-Host \"[Error] $Browser is not installed. Please ensure it's installed System-Wide prior to running this script.\"\r\n        exit 1\r\n    }\r\n\r\n    $UserProfiles = Get-UserHives -Type \"All\"\r\n    # Loop through each profile on the machine\r\n    Foreach ($UserProfile in $UserProfiles) {\r\n        # Load User ntuser.dat if it's not already loaded\r\n        If (($ProfileWasLoaded = Test-Path Registry::HKEY_USERS\\$($UserProfile.SID)) -eq $false) {\r\n            Start-Process -FilePath \"cmd.exe\" -ArgumentList \"\/C reg.exe LOAD HKU\\$($UserProfile.SID) `\"$($UserProfile.UserHive)`\"\" -Wait -WindowStyle Hidden\r\n        }\r\n\r\n        # The hex date and user experience don't really change\r\n        $userExperience = \"User Choice set via Windows User Experience {D18B6DD5-6124-4341-9318-804003BAFA0B}\"\r\n        $hexDateTime = Get-HexDateTime\r\n\r\n\r\n        Write-Host \"`nSetting default browser of $Browser for $($UserProfile.UserName).\"\r\n\r\n        # Set protocol association registry keys\r\n        $Protocols | ForEach-Object {\r\n            Write-Host \"Setting \"\r\n            $Protocol = $_\r\n\r\n            $ToBeHashed = \"$Protocol$($UserProfile.SID)$urlID$hexDateTime$userExperience\".ToLower()\r\n            $Hash = Get-Hash -BaseInfo $ToBeHashed\r\n\r\n            Set-RegKey -Path \"Registry::HKEY_USERS\\$($UserProfile.SID)\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\$Protocol\\UserChoice\" -Name \"Hash\" -Value $Hash -PropertyType String\r\n            Set-RegKey -Path \"Registry::HKEY_USERS\\$($UserProfile.SID)\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\$Protocol\\UserChoice\" -Name \"ProgId\" -Value $urlID -PropertyType String\r\n        }\r\n\r\n        # Set file association registry keys\r\n        $Files | ForEach-Object {\r\n            Write-Host \"Setting \"\r\n            $File = $_\r\n\r\n            $ToBeHashed = \".$File$($UserProfile.SID)$htmlID$hexDateTime$userExperience\".ToLower()\r\n            $Hash = Get-Hash -BaseInfo $ToBeHashed\r\n\r\n            Set-RegKey -Path \"Registry::HKEY_USERS\\$($UserProfile.SID)\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\$File\\UserChoice\" -Name \"Hash\" -Value $Hash -PropertyType String\r\n            Set-RegKey -Path \"Registry::HKEY_USERS\\$($UserProfile.SID)\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\$File\\UserChoice\" -Name \"ProgId\" -Value $htmlID -PropertyType String\r\n            Set-RegKey -Path \"Registry::HKEY_USERS\\$($UserProfile.SID)\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.$File\\UserChoice\" -Name \"Hash\" -Value $Hash -PropertyType String\r\n            Set-RegKey -Path \"Registry::HKEY_USERS\\$($UserProfile.SID)\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.$File\\UserChoice\" -Name \"ProgId\" -Value $htmlID -PropertyType String\r\n        }\r\n            \r\n        # Unload NTuser.dat\r\n        If ($ProfileWasLoaded -eq $false) {\r\n            [gc]::Collect()\r\n            Start-Sleep 1\r\n            Start-Process -FilePath \"cmd.exe\" -ArgumentList \"\/C reg.exe UNLOAD HKU\\$($UserProfile.SID)\" -Wait -WindowStyle Hidden | Out-Null\r\n        }\r\n    }\r\n\r\n    # Restart explorer if requested\r\n    if ($RestartExplorer) {\r\n        Write-Host \"`nRestarting Explorer.exe as requested.\"\r\n\r\n        # Stop all instances of Explorer\r\n        Get-Process explorer | Stop-Process -Force\r\n        \r\n        Start-Sleep -Seconds 1\r\n\r\n        # Restart Explorer if not running as System and Explorer is not already running\r\n        if (!(Test-IsSystem) -and !(Get-Process -Name \"explorer\")) {\r\n            Start-Process explorer.exe\r\n        }\r\n    }\r\n}\r\nend {\r\n    \r\n    \r\n    \r\n}<\/pre>\n<p>&nbsp;<\/p>\n\n<div class=\"blog-cta-new blog-cta-style-1\"><div class=\"cta-left\"><h2><\/h2><p><\/p><\/div><div class=\"cta-right\"><a class=\"button\" href=\"\"><\/a><\/div><\/div>\n<h2>An\u00e1lisis detallado<\/h2>\n<p>El script para establecer un navegador predeterminado interact\u00faa con el registro de Windows, centr\u00e1ndose espec\u00edficamente en los archivos de registro espec\u00edficos del usuario que almacenan la configuraci\u00f3n predeterminada de las aplicaciones. Aqu\u00ed tienes un desglose paso a paso de c\u00f3mo funciona el script:<\/p>\n<h3>1. Inicializaci\u00f3n del script<\/h3>\n<ul>\n<li>El script comienza verificando si se est\u00e1 ejecutando con privilegios elevados (acceso de Administrador). En caso contrario, el script finalizar\u00e1, garantizando que s\u00f3lo el personal autorizado pueda realizar cambios en todo el sistema.<\/li>\n<\/ul>\n<h3>2. Gesti\u00f3n de par\u00e1metros<\/h3>\n<ul>\n<li>Se aceptan dos par\u00e1metros: el navegador a establecer como predeterminado y un interruptor para reiniciar el proceso Explorer.exe. El par\u00e1metro de navegador acepta \u00abMozilla Firefox\u00bb, \u00abGoogle Chrome\u00bb o \u00abMicrosoft Edge\u00bb y, por defecto, lo que se establezca en la variable de entorno si no se proporciona directamente.<\/li>\n<\/ul>\n<h3>3. Validaci\u00f3n del navegador<\/h3>\n<ul>\n<li>Antes de continuar, el script comprueba si el navegador especificado est\u00e1 instalado en el sistema buscando en el registro su clave de desinstalaci\u00f3n. Si el navegador no est\u00e1 instalado, el script sale con un mensaje de error.<\/li>\n<\/ul>\n<h3>4. Gesti\u00f3n de perfiles<\/h3>\n<ul>\n<li>El script recupera una lista de todos los perfiles de usuario de la m\u00e1quina examinando el registro en busca de configuraciones espec\u00edficas de usuario. Identifica el identificador de seguridad (SID) de cada usuario y carga su colmena de registro para modificar la configuraci\u00f3n predeterminada del navegador.<\/li>\n<\/ul>\n<h3>5. Configuraci\u00f3n del protocolo por defecto y asociaciones de archivos<\/h3>\n<ul>\n<li>Para cada perfil de usuario, el script modifica el registro para establecer el navegador seleccionado como gestor predeterminado para los tipos de archivo HTTP, HTTPS, HTM, HTML y XHTML. Esto implica la generaci\u00f3n de un hash \u00fanico para las configuraciones con el fin de garantizar que Windows las reconozca como v\u00e1lidas y seguras.<\/li>\n<\/ul>\n<h3>6. Reiniciar Explorer (opcional)<\/h3>\n<ul>\n<li>Si se utiliza el modificador -RestartExplorer, el script detiene y reinicia el proceso Explorer.exe. Este paso es necesario para aplicar inmediatamente los cambios y actualizar los iconos del escritorio asociados a los tipos de archivo afectados.<\/li>\n<\/ul>\n<h2>Posibles casos de uso<\/h2>\n<p>Imagina a un administrador inform\u00e1tico que gestiona una gran red corporativa con cientos de usuarios. La empresa ha optado recientemente por Firefox como navegador predeterminado debido a sus caracter\u00edsticas de seguridad mejoradas.<\/p>\n<p>En lugar de configurar manualmente Firefox como navegador por defecto en el perfil de cada usuario, el administrador puede ejecutar este script para establecer un navegador predeterminado en toda la red, asegur\u00e1ndose de que cada usuario, independientemente de su frecuencia de inicio de sesi\u00f3n o del estado de su perfil, utiliza Firefox por defecto. Esto no s\u00f3lo ahorra tiempo, sino que tambi\u00e9n reduce la probabilidad de errores de los usuarios o de incumplimiento de las pol\u00edticas corporativas.<\/p>\n<h2>Comparaciones<\/h2>\n<p>Aunque este script de PowerShell ofrece un enfoque simplificado para establecer un navegador predeterminado, existen otros m\u00e9todos para lograr el mismo resultado, como utilizar la directiva de grupo o desplegar una herramienta de gesti\u00f3n de software. La directiva de grupo proporciona una forma m\u00e1s centralizada de aplicar la configuraci\u00f3n del navegador, pero puede ser compleja de configurar y puede no cubrir todos los escenarios, especialmente con perfiles espec\u00edficos de usuario.<\/p>\n<p>Por otro lado, las herramientas de gesti\u00f3n de software suelen conllevar costes adicionales y requieren una curva de aprendizaje. Este script logra un equilibrio al ofrecer una soluci\u00f3n personalizable y sin coste que se integra directamente en el entorno Windows existente.<\/p>\n<h2>FAQ<\/h2>\n<h3>P: \u00bfSe puede utilizar este script en sistemas con versiones de Windows anteriores a Windows 10?<\/h3>\n<p>R: El script est\u00e1 dise\u00f1ado para Windows 10 y versiones posteriores, ya que usa estructuras de registro y protocolos espec\u00edficos que pueden no estar disponibles en versiones anteriores de Windows.<\/p>\n<h3>P: \u00bfQu\u00e9 ocurre si un usuario instala un nuevo navegador despu\u00e9s de ejecutar el script?<\/h3>\n<p>R: Si se instala un nuevo navegador despu\u00e9s de ejecutar el script, puede intentar establecerse como predeterminado. En tales casos, si se vuelve a ejecutar el script, se volver\u00e1n a aplicar los ajustes deseados.<\/p>\n<h3>P: \u00bfPuede modificarse el script para incluir otros navegadores que no figuran en los par\u00e1metros?<\/h3>\n<p>R: S\u00ed, el script puede ser adaptado para soportar otros navegadores a\u00f1adiendo sus respectivos identificadores de protocolo y gestor de archivos.<\/p>\n<h2>Implicaciones<\/h2>\n<p>Mediante este script, los profesionales de TI pueden imponer la coherencia del navegador en todos los perfiles de usuario, lo que resulta esencial para la seguridad y el cumplimiento de las normativas. Sin embargo, los administradores deben ser conscientes de las implicaciones potenciales, como la anulaci\u00f3n de las preferencias del usuario y la necesidad de asegurarse de que todos los navegadores necesarios est\u00e1n instalados en todo el sistema antes de ejecutar el script.<\/p>\n<h2>Recomendaciones<\/h2>\n<ul>\n<li><strong>Haz pruebas en un entorno controlado<\/strong>: antes de desplegar este script en toda la red, es aconsejable probarlo en un entorno controlado para asegurarte de que se comporta como se espera.<\/li>\n<li><strong>Aseg\u00farate de que todos los navegadores est\u00e1n instalados<\/strong>: comprueba que el navegador predeterminado seleccionado est\u00e9 instalado en todos los sistemas en los que se ejecutar\u00e1 el script.<\/li>\n<li><strong>Ten en cuenta la comunicaci\u00f3n con el usuario<\/strong>: informa a los usuarios del cambio, especialmente si se van a anular las preferencias predeterminadas de tu navegador.<\/li>\n<\/ul>\n<h2>Reflexiones finales<\/h2>\n<p>Para los profesionales de TI y los MSP, la gesti\u00f3n eficaz de los entornos de usuario es fundamental. Este script PowerShell ofrece una soluci\u00f3n robusta para estandarizar el navegador por defecto en todos los perfiles de usuario de un sistema Windows. <a href=\"https:\/\/www.ninjaone.com\/es\/\" target=\"_blank\" rel=\"noopener\">NinjaOne<\/a> proporciona herramientas completas para la gesti\u00f3n de endpoints, incluyendo el despliegue de software y gesti\u00f3n de perfiles de usuario, y este script puede ser un excelente complemento, ofreciendo un control pormenorizado sobre la configuraci\u00f3n del navegador.<\/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":[4259],"class_list":["post-353797","script_hub","type-script_hub","status-publish","hentry","script_hub_category-windows"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/script_hub\/353797","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/script_hub"}],"about":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/types\/script_hub"}],"author":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/users\/35"}],"replies":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/comments?post=353797"}],"wp:attachment":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/media?parent=353797"}],"wp:term":[{"taxonomy":"script_hub_category","embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/operating_system?post=353797"},{"taxonomy":"use_cases","embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/use_cases?post=353797"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}