Como habilitar o Microsoft Store para todos os usuários usando o PowerShell

À medida que as organizações integram cada vez mais soluções digitais, o gerenciamento e a implementação de software tornam-se fundamentais. Dentro dessa estrutura, a Windows Store da Microsoft é um recurso fundamental, oferecendo um vasto repositório de aplicativos e serviços. Entender como habilitar o Microsoft Store para todos os usuários pode ser fundamental, especialmente para operações de TI em grande escala.

Histórico

A Windows Store da Microsoft foi introduzida para simplificar o processo de implantação de aplicativos. No entanto, pode haver cenários em que a Windows Store esteja desativada por padrão ou por meio de determinadas políticas. Para os profissionais de TI e os provedores de serviços gerenciados (MSPs), ter a capacidade de habilitá-lo em vários perfis de usuário não é apenas uma conveniência – é uma necessidade. Digite o script fornecido, uma ferramenta poderosa adaptada para habilitar a Windows Store para todos os usuários, tanto os existentes quanto os recém-criados.

O roteiro:

#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 {}

 

Acesse mais de 300 scripts no NinjaOne Dojo

Obter acesso

Detalhamento

O script funciona em uma sequência clara:

Inicialização:

  • Duas funções, Test-IsElevated e Test-IsSystem, verificam os privilégios necessários do script.
  • Em seguida, o script configura outra função, Set-HKProperty, para facilitar as operações de registro.
  • Uma função mais complexa, Get-UserHives, recupera caminhos de registro para todos os usuários reais.

Processo:

  • Define o caminho, o nome e o valor para ativar a Windows Store.
  • Recupera perfis de usuário e verifica se há regras de bloqueio de aplicativos que possam impedir o acesso à Windows Store, fazendo alterações conforme necessário.
  • Itera através de cada perfil de usuário, manipulando o registro para garantir que a Windows Store esteja ativada.
  • Valida o sucesso da operação.

Rescisão:

  • O script termina fornecendo feedback de status.

Casos de uso em potencial

Estudo de caso: Imagine uma grande instituição de ensino migrando sua infraestrutura de software. Eles se integraram recentemente ao ecossistema da Microsoft, mas descobriram que a Windows Store é inacessível para alunos e professores. Em vez de configurar individualmente milhares de perfis, nosso script resolve o problema de uma só vez, garantindo o acesso oportuno de todos aos aplicativos necessários.

Comparações

Embora as configurações manuais ou o emprego de ferramentas separadas sejam opções, elas podem ser complicadas e propensas a erros, especialmente em uma escala maior. Esse script automatiza e simplifica o processo, reduzindo muito a chance de erros e economizando tempo.

Implicações

Embora o script simplifique bastante a ativação da Windows Store, o acesso não monitorado pode expor os usuários a aplicativos não aprovados. Os profissionais de TI devem garantir um equilíbrio entre acessibilidade e segurança, considerando as possíveis vulnerabilidades.

Recomendações

  • Sempre faça backup das configurações atuais antes de implementar esses scripts.
  • Revise regularmente os aplicativos habilitados na Windows Store para garantir que eles estejam em conformidade com as diretrizes organizacionais.
  • Eduque continuamente os usuários sobre práticas seguras de aplicativos.

Considerações finais

O NinjaOne, com sua abordagem holística de TI, complementa ferramentas como esse script, oferecendo gerenciamento simplificado e supervisão mais abrangente. Com a integração de ambos, os profissionais de TI podem não apenas “habilitar o Microsoft Store” sem problemas, mas também garantir seu uso otimizado e seguro.

FAQs

Sim, requer privilégios elevados.

Ele foi projetado para Windows 10 e Server 2016 em diante.

Sim, as exclusões podem ser tratadas por meio dos parâmetros da função Get-UserHives.

Próximas etapas

Montar uma equipe de TI eficaz requer uma solução centralizada que seja a principal ferramenta de entrega de serviços. Com NinjaOne, a TI monitora, gerencia, protege e oferece suporte a todos os dispositivos, onde quer que estejam, dispensando infraestrutura complexa no local.

Saiba mais sobre a solução NinjaOne Remote Script Deployment, agende uma demonstração, ou inicie sua avaliação gratuita da plataforma NinjaOne.

Categories:

You might also like

Como instalar o .NET Framework 4 usando o PowerShell

Como gerar um relatório abrangente de LAN sem fio usando o PowerShell

Como habilitar o Microsoft Store para todos os usuários usando o PowerShell

Como detectar software de acesso remoto em um sistema usando o PowerShell

Como identificar unidades desbloqueadas e totalmente descriptografadas usando o PowerShell

Como detectar o tempo ocioso do usuário usando o PowerShell