Ver demo×
×

¡Vean a NinjaOne en acción!

Al enviar este formulario, acepto la política de privacidad de NinjaOne.

Cómo habilitar Windows Store para todos los usuarios mediante PowerShell

A medida que las organizaciones integran cada vez más soluciones digitales, la gestión y el despliegue del software adquieren una importancia capital. En este contexto, la Windows Store de Microsoft se erige como una característica fundamental, ya que ofrece un amplio repositorio de aplicaciones y servicios. Entender cómo habilitar Windows Store para todos los usuarios puede ser clave, especialmente para las operaciones de TI a gran escala.

Antecedentes

Windows Store de Microsoft se introdujo para simplificar el proceso de despliegue de aplicaciones. Sin embargo, puede haber situaciones en las que la Windows Store esté deshabilitada por defecto o a través de ciertas políticas. Para los profesionales de TI y los proveedores de servicios gestionados (MSP), tener la capacidad de activarlo en varios perfiles de usuario no es sólo una comodidad, sino una necesidad. Descubre el script que te presentamos a continuación, una potente herramienta diseñada para habilitar Windows Store para todos los usuarios, tanto los existentes como los de nueva creación.

El script para habilitar Windows Store para todos los usuarios

#Requires -Version 5.1

<#
.SYNOPSIS
    Enables the Windows Store for all users and newly created users.
.DESCRIPTION
    Enables the Windows Store for all users and newly created users.
    No parameters needed
    Enables the Windows Store for all users and newly created users.
.EXAMPLE
    (No Parameters)
    Enables the Windows Store for all users and newly created users.
.OUTPUTS
    None
.NOTES
    Minimum OS Architecture Supported: Windows 10, Server 2016
    Release Notes:
    Initial Release
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.
    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. 
    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. 
    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. 
    Warranty Disclaimer: The script is provided “as is” and “as available”, 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. 
    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. 
    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. 
    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
#>

[CmdletBinding()]
param ()

begin {
    function Test-IsElevated {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
    }

    function Test-IsSystem {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        return $id.Name -like "NT AUTHORITY*" -or $id.IsSystem
    }

    if (!(Test-IsElevated) -and !(Test-IsSystem)) {
        Write-Error -Message "Access Denied. Please run with Administrator privileges."
        exit 1
    }
    
    # Setting up some functions to be used later.
    function Set-HKProperty {
        param (
            $Path,
            $Name,
            $Value,
            [ValidateSet('DWord', 'QWord', 'String', 'ExpandedString', 'Binary', 'MultiString', 'Unknown')]
            $PropertyType = 'DWord'
        )
        if (-not $(Test-Path -Path $Path)) {
            # Check if path does not exist and create the path
            New-Item -Path $Path -Force | Out-Null
        }
        if ((Get-ItemProperty -Path $Path -Name $Name -ErrorAction Ignore)) {
            # Update property and print out what it was changed from and changed to
            $CurrentValue = (Get-ItemProperty -Path $Path -Name $Name -ErrorAction Ignore).$Name
            try {
                Set-ItemProperty -Path $Path -Name $Name -Value $Value -Force -Confirm:$false -ErrorAction Stop | Out-Null
            }
            catch {
                Write-Error "[Error] Unable to Set registry key for $Name please see below error!"
                Write-Error $_
                exit 1
            }
            Write-Host "$Path$Name changed from $CurrentValue to $($(Get-ItemProperty -Path $Path -Name $Name -ErrorAction Ignore).$Name)"
        }
        else {
            # Create property with value
            try {
                New-ItemProperty -Path $Path -Name $Name -Value $Value -PropertyType $PropertyType -Force -Confirm:$false -ErrorAction Stop | Out-Null
            }
            catch {
                Write-Error "[Error] Unable to Set registry key for $Name please see below error!"
                Write-Error $_
                exit 1
            }
            Write-Host "Set $Path$Name to $($(Get-ItemProperty -Path $Path -Name $Name -ErrorAction Ignore).$Name)"
        }
    }

    # This will get all the registry path's for all actual users (not system or network service account but actual users.)
    function Get-UserHives {
        param (
            [Parameter()]
            [ValidateSet('AzureAD', 'DomainAndLocal', 'All')]
            [String]$Type = "All",
            [Parameter()]
            [String[]]$ExcludedUsers,
            [Parameter()]
            [switch]$IncludeDefault
        )

        # User account SID's follow a particular patter depending on if they're azure AD or a Domain account or a local "workgroup" account.
        $Patterns = switch ($Type) {
            "AzureAD" { "S-1-12-1-(d+-?){4}$" }
            "DomainAndLocal" { "S-1-5-21-(d+-?){4}$" }
            "All" { "S-1-12-1-(d+-?){4}$" ; "S-1-5-21-(d+-?){4}$" } 
        }

        # 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. 
        $UserProfiles = Foreach ($Pattern in $Patterns) { 
            Get-ItemProperty "HKLM:SOFTWAREMicrosoftWindows NTCurrentVersionProfileList*" |
                Where-Object { $_.PSChildName -match $Pattern } | 
                Select-Object @{Name = "SID"; Expression = { $_.PSChildName } }, 
                @{Name = "UserHive"; Expression = { "$($_.ProfileImagePath)NTuser.dat" } }, 
                @{Name = "UserName"; Expression = { "$($_.ProfileImagePath | Split-Path -Leaf)" } }
        }

        # There are some situations where grabbing the .Default user's info is needed.
        switch ($IncludeDefault) {
            $True {
                $DefaultProfile = "" | Select-Object UserName, SID, UserHive
                $DefaultProfile.UserName = "Default"
                $DefaultProfile.SID = "DefaultProfile"
                $DefaultProfile.Userhive = "$env:SystemDriveUsersDefaultNTUSER.DAT"

                # It was easier to write-output twice than combine the two objects.
                $DefaultProfile | Where-Object { $ExcludedUsers -notcontains $_.UserName } | Write-Output
            }
        }

        $UserProfiles | Where-Object { $ExcludedUsers -notcontains $_.UserName } | Write-Output
    }
}
process {
    $Path = "SoftwarePoliciesMicrosoftWindowsStore"
    $Name = "RemoveWindowsStore"
    $Value = 0

    # Get each user profile SID and Path to the profile. If there are any exclusions we'll have to take them into account.
    $UserProfiles = Get-UserHives -IncludeDefault

    # If the Disable-WindowsStore script was used we'll need to check applocker
    [xml]$AppLockerXML = Get-AppLockerPolicy -Local -Xml
    if ($AppLockerXML.AppLockerPolicy.RuleCollection.FilePublisherRule) {
        $AppLockerXML.AppLockerPolicy.RuleCollection.FilePublisherRule | ForEach-Object { 
            if (($_.Action -eq "Deny") -and ($_.Conditions.FilePublisherCondition.ProductName -like "*Microsoft.WindowsStore*")) {
                Write-Warning "Removing AppLocker file publishing rules for the Windows Store!" 
                [Void]$_.ParentNode.RemoveChild($_)
            }       
        }

        if($AppLockerXML.AppLockerPolicy.RuleCollection.FilePublisherRule.id.Count -eq "1" -and $AppLockerXML.AppLockerPolicy.RuleCollection.FilePublisherRule.Name -eq "(Default Rule) All signed packaged apps"){
            
            $AppLockerXML.AppLockerPolicy.RuleCollection.FilePublisherRule | ForEach-Object {
                if($_.ParentNode){
                    [Void]$_.ParentNode.RemoveChild($_)
                }
            }

            $AppLockerXML.AppLockerPolicy.RuleCollection | ForEach-Object {
                if($_.Type -eq "Appx"){
                    $_.EnforcementMode = "NotConfigured"
                }
            }
        }

        $AppLockerXML.Save("$env:TEMPapplocker.xml")
        Set-AppLockerPolicy -XmlPolicy "$env:TEMPapplocker.xml"
        Remove-Item "$env:TEMPapplocker.xml"
    }

    $script:DisabledWinRun = $true
    $failedUsers = @()
    # Loop through each profile on the machine
    Foreach ($UserProfile in $UserProfiles) {
        # Load User ntuser.dat if it's not already loaded
        If (($ProfileWasLoaded = Test-Path Registry::HKEY_USERS$($UserProfile.SID)) -eq $false) {
            Start-Process -FilePath "cmd.exe" -ArgumentList "/C reg.exe LOAD HKU$($UserProfile.SID) `"$($UserProfile.UserHive)`"" -Wait -WindowStyle Hidden
        }
        # Manipulate the registry
        $key = "Registry::HKEY_USERS$($UserProfile.SID)$($Path)"
        Set-HKProperty -Path $key -Name $Name -Value $Value -PropertyType DWord

        if ($(Get-ItemProperty -Path $key -Name $Name -ErrorAction Ignore).$Name -ne $Value) {
            $script:DisabledWinRun = $false
            $failedUsers += $UserProfile.UserName
        }
        
        # Unload NTuser.dat
        If ($ProfileWasLoaded -eq $false) {
            [gc]::Collect()
            Start-Sleep 1
            Start-Process -FilePath "cmd.exe" -ArgumentList "/C reg.exe UNLOAD HKU$($UserProfile.SID)" -Wait -WindowStyle Hidden | Out-Null
        }
    }

    Start-Sleep -Seconds 30
    if ($script:DisabledWinRun) {
        # All $UserProfiles updated
        exit 0
    }
    else {
        $failedUsers | ForEach-Object { Write-Error "Failed to update user `"$_`"" }
        Write-Error "One or more user profiles failed to update"
        exit 1
    }
}
end {}

 

Accede a más de 300 scripts en el Dojo de NinjaOne

Obtén acceso

Análisis detallado

El script sigue una secuencia clara:

Inicialización:

  • Dos funciones, Test-IsElevated y Test-IsSystem, comprueban los privilegios necesarios del script.
  • A continuación, el script establece otra función, Set-HKProperty, para facilitar las operaciones de registro.
  • Una función más compleja, Get-UserHives, recupera las rutas de registro de todos los usuarios reales.

Proceso:

  • Define la ruta, el nombre y el valor para habilitar la Windows Store.
  • Recupera los perfiles de usuario y comprueba si existen reglas de bloqueo de aplicaciones que puedan impedir el acceso a la Windows Store, realizando las modificaciones necesarias.
  • Recorre cada perfil de usuario, manipulando el registro para asegurarse de que Windows Store está habilitada.
  • Valida el éxito de la operación.

Resolución:

  • El script finaliza proporcionando información sobre el estado.

Posibles casos de uso

Estudio de caso: Imagina una gran institución educativa que está en el proceso de migrar su infraestructura de software. Recientemente se han integrado en el ecosistema de Microsoft, pero descubren que la Windows Store es inaccesible para estudiantes y profesores. En lugar de configurar individualmente miles de perfiles, nuestro script resuelve el problema de una sola vez, garantizando a todos el acceso a las aplicaciones necesarias.

Comparaciones

Aunque las configuraciones manuales o el empleo de herramientas independientes son opciones, pueden resultar engorrosas y propensas a errores, sobre todo a gran escala. Este script automatiza y agiliza el proceso, reduciendo en gran medida la posibilidad de errores y ahorrando tiempo.

Preguntas frecuentes

  • ¿Es necesario tener privilegios de administrador para ejecutar este script?
    Sí, requiere privilegios elevados.
  • ¿Funcionará este script en versiones anteriores de Windows?
    Está diseñado para Windows 10 y Server 2016 en adelante.
  • ¿Se puede excluir a determinados usuarios?
    Sí, las exclusiones pueden gestionarse a través de los parámetros de la función Get-UserHives.

Implicaciones

Aunque el script simplifica enormemente la activación de la Windows Store, el acceso no supervisado podría exponer a los usuarios a aplicaciones no aprobadas. Los profesionales de TI deben garantizar un equilibrio entre accesibilidad y seguridad, teniendo en cuenta las posibles vulnerabilidades.

Recomendaciones

  • Haz siempre una copia de seguridad de la configuración actual antes de desplegar este tipo de scripts.
  • Revisa periódicamente las aplicaciones habilitadas en Windows Store para asegurarte de que cumplen las directrices de la organización.
  • Crea conciencia continuamente entre los usuarios sobre prácticas seguras con las aplicaciones.

Reflexiones finales

NinjaOne, con su enfoque global a las TI, es el complemento perfecto a herramientas como este script, ofreciendo una gestión simplificada y una supervisión más exhaustiva. Al integrar ambos, los profesionales de TI no sólo pueden «habilitar Windows Store» sin problemas, sino también garantizar su uso optimizado y seguro.

Próximos pasos

La creación de un equipo de TI próspero y eficaz requiere contar con una solución centralizada que se convierta en tu principal herramienta de prestación de servicios. NinjaOne permite a los equipos de TI supervisar, gestionar, proteger y dar soporte a todos sus dispositivos, estén donde estén, sin necesidad de complejas infraestructuras locales.

Obtén más información sobre NinjaOne Endpoint Management, echa un vistazo a un tour en vivo o comienza tu prueba gratuita de la plataforma NinjaOne.

Quizá también te interese…

Términos y condiciones de NinjaOne

Al hacer clic en el botón «Acepto» que aparece a continuación, estás aceptando los siguientes términos legales, así como nuestras Condiciones de uso:

  • Derechos de propiedad: NinjaOne posee y seguirá poseyendo todos los derechos, títulos e intereses sobre el script (incluidos los derechos de autor). NinjaOne concede al usuario una licencia limitada para utilizar el script de acuerdo con estos términos legales.
  • Limitación de uso: sólo podrás utilizar el script para tus legítimos fines personales o comerciales internos, y no podrás compartirlo con terceros.
  • Prohibición de republicación: Bajo ninguna circunstancia está permitido volver a publicar el script en ninguna biblioteca de scripts que pertenezca o esté bajo el control de cualquier otro proveedor de software.
  • Exclusión de garantía: El script se proporciona «»tal cual» y «según disponibilidad», sin garantía de ningún tipo. NinjaOne no promete ni garantiza que el script esté libre de defectos o que satisfaga las necesidades o expectativas específicas del usuario.
  • Asunción de riesgos: El uso que el usuario haga del script corre por su cuenta y riesgo. El usuario reconoce que existen ciertos riesgos inherentes al uso del script, y entiende y asume cada uno de esos riesgos.
  • Renuncia y exención: El usuario no hará responsable a NinjaOne de cualquier consecuencia adversa o no deseada que resulte de su uso del script y renuncia a cualquier derecho o recurso legal o equitativo que pueda tener contra NinjaOne en relación con su uso del script.
  • CLUF: Si el usuario es cliente de NinjaOne, su uso del script está sujeto al Contrato de Licencia para el Usuario Final (CLUF).