Demo ansehen×
×

Sehen Sie NinjaOne in Aktion!

Mit dem Absenden dieses Formulars akzeptiere ich die Datenschutzerklärung von NinjaOne.

Automatisierung der IT: Ein Skript zum Deaktivieren des Microsoft Store im gesamten Netzwerk

Die Verwaltung von Benutzerberechtigungen und Anwendungszugriff in einem Unternehmensnetzwerk kann eine schwierige und zeitraubende Aufgabe sein. Dennoch können Skripte, die diese Aufgaben automatisch erledigen, eine große Hilfe für IT-Profis und Managed Service Provider (MSPs) sein. Heute konzentrieren wir uns auf ein PowerShell-Skript, mit dem der Windows Store für alle Benutzer:innen und neu erstellte Benutzer:innen mit AppLockerdeaktiviert werden kann. Dieses Skript ist auf Windows 10- und Server 2016-Systeme zugeschnitten und bietet mehrere konfigurierbare Optionen, wie z. B. den Ausschluss bestimmter Benutzer:innen und die Beschränkung auf bestehende Benutzer:innen.

In diesem Blogbeitrag gehen wir auf die verschiedenen Aspekte des Skripts ein und erläutern, warum es eine unschätzbare Ergänzung für Ihre IT-Toolbox sein kann.

Das Skript

#Requires -Version 5.1

<#
.SYNOPSIS
    Disables the Windows Store for all users and newly created users using AppLocker. Can be given a comma separated list
    of users to exclude.
.DESCRIPTION
    Disables the Windows Store for all users and newly created users using AppLocker. Can be given a comma separated list
    of users to exclude.
.EXAMPLE
    (No Parameters)
    
    WARNING: Creating AppLocker rule for user or group "Interactive"...
    Registry::HKEY_USERSDefaultProfileSoftwarePoliciesMicrosoftWindowsStoreRemoveWindowsStore changed from 0 to 1
    Registry::HKEY_USERSS-1-5-21-3870645062-3653562310-3850680542-1001SoftwarePoliciesMicrosoftWindowsStoreRemoveWindowsStore changed from 0 to 1
    Registry::HKEY_USERSS-1-5-21-3870645062-3653562310-3850680542-1002SoftwarePoliciesMicrosoftWindowsStoreRemoveWindowsStore changed from 0 to 1

PARAMETER: -ExcludeUsers "Test1,Test2"
    A comma seperated list of users to exclude. Please note newly created users will not have the windows store disabled.
.EXAMPLE
    -ExcludeUsers "Test1,Test2"

    WARNING: The Following Users and newly created users will not have the windows store disabled. Test1 Test2
    Registry::HKEY_USERSS-1-5-21-3870645062-3653562310-3850680542-1002SoftwarePoliciesMicrosoftWindowsStoreRemoveWindowsStore changed from 0 to 1
    WARNING: Creating AppLocker rule for user or group "tuser"...

PARAMETER: -ExistingUsersOnly
    This will disable the Windows store for existing users only.
.EXAMPLE
    -ExistingUsersOnly

    WARNING: Only existing users will have the windows store disabled!
    Set Registry::HKEY_USERSS-1-5-21-3870645062-3653562310-3850680542-1001SoftwarePoliciesMicrosoftWindowsStoreRemoveWindowsStore to 1
    WARNING: Creating AppLocker rule for user or group "kbohlander"...
    Set Registry::HKEY_USERSS-1-5-21-3870645062-3653562310-3850680542-1002SoftwarePoliciesMicrosoftWindowsStoreRemoveWindowsStore to 1
    WARNING: Creating AppLocker rule for user or group "tuser"...
.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/de/nutzungsbedingungen
    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 (
    [Parameter()]
    [String[]]$ExcludeUsers,
    [Parameter()]
    [Switch]$ExistingUsersOnly
)

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"
                $DefaultProfile | Where-Object { $ExcludedUsers -notcontains $_.UserName }
            }
        }

        $UserProfiles | Where-Object { $ExcludedUsers -notcontains $_.UserName }
    }

    function New-WindowStoreBlock {
        param(
            [Parameter()]
            [String]$User
        )

        Write-Warning "Creating AppLocker rule for user or group `"$User`"..."
        [xml]$AppLockerTemplate = Get-AppXPackage -AllUsers -Name "Microsoft.WindowsStore" | Get-AppLockerFileInformation | New-AppLockerPolicy -User "$User" -Optimize -Xml
        $AppLockerTemplate.AppLockerPolicy.RuleCollection.EnforcementMode = "Enabled"
        $AppLockerTemplate.AppLockerPolicy.RuleCollection.FilePublisherRule.Action = "Deny"
        $AppLockerTemplate.AppLockerPolicy.RuleCollection.FilePublisherRule.Conditions.FilePublisherCondition.BinaryVersionRange.LowSection = "*"
        $AppLockerTemplate.Save("$env:TEMPapplocker.xml")
        Set-AppLockerPolicy -XmlPolicy "$env:TEMPapplocker.xml" -Merge
        Remove-Item "$env:TEMPapplocker.xml"
    }
}
process {
    if ($env:ExistingUsersOnly) { $ExistingUsersOnly = $env:ExistingUsersOnly }
    # This registry key only works sometimes. It's worth setting if its an older windows build or has an older version of the store installed.
    $Path = "SoftwarePoliciesMicrosoftWindowsStore"
    $Name = "RemoveWindowsStore"
    $Value = 1
    
    # Get each user profile SID and Path to the profile. If there are any exclusions we'll have to take them into account.
    if ($ExcludeUsers -or $env:ExcludeUsers -or $ExistingUsersOnly) {
        if ($env:ExcludeUsers) {
            $ToBeExcluded = @()
            $ToBeExcluded += $env:ExcludeUsers.split(",").trim()
        }

        if ($ExcludeUsers) {
            $ToBeExcluded = @()
            $ToBeExcluded += $ExcludeUsers.split(",").trim()
        }

        if ($ToBeExcluded) { 
            Write-Warning "The Following Users and newly created users will not have the windows store disabled. $ToBeExcluded"
            $UserProfiles = Get-UserHives -ExcludedUsers $ToBeExcluded 
        }
        elseif ($ExistingUsersOnly) { 
            Write-Warning "Only existing users will have the windows store disabled!"
            $UserProfiles = Get-UserHives 
        }
    }
    else {
        $UserProfiles = Get-UserHives -IncludeDefault
    }

    [xml]$AppLockerXML = '<AppLockerPolicy Version="1"><RuleCollection Type="Appx" EnforcementMode="Enabled"><FilePublisherRule Id="a9e18c21-ff8f-43cf-b9fc-db40eed693ba" Name="(Default Rule) All signed packaged apps" Description="Allows members of the Everyone group to run packaged apps that are signed." UserOrGroupSid="S-1-1-0" Action="Allow"><Conditions><FilePublisherCondition PublisherName="*" ProductName="*" BinaryName="*"><BinaryVersionRange LowSection="0.0.0.0" HighSection="*" /></FilePublisherCondition></Conditions></FilePublisherRule></RuleCollection></AppLockerPolicy>'
    $AppLockerXML.Save("$env:TEMPapplocker.xml")
    Set-AppLockerPolicy -XmlPolicy "$env:TEMPapplocker.xml" -Merge
    Remove-Item "$env:TEMPapplocker.xml"

    if (!$ToBeExcluded -and !$ExistingUsersOnly) {
        New-WindowStoreBlock -User "Interactive"
    }

    $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

        # This will be our applocker policy we'll need to tweak it prior to running it
        if ($UserProfile.SID -notlike "DefaultProfile") {
            if ($ToBeExcluded -or $ExistingUsersOnly) {
                New-WindowStoreBlock -User "$($UserProfile.UserName)"
            }
        }

        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-Process -FilePath "cmd.exe" -ArgumentList "/C sc config `"AppIDSvc`" start=auto & net start `"AppIDSvc`"" -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 {}

|

#Requires -Version 5.1

<#
.SYNOPSIS
    Disables the Windows Store for all users and newly created users using AppLocker. Can be given a comma separated list
    of users to exclude.
.DESCRIPTION
    Disables the Windows Store for all users and newly created users using AppLocker. Can be given a comma separated list
    of users to exclude.
.EXAMPLE
    (No Parameters)
    
    WARNING: Creating AppLocker rule for user or group "Interactive"...
    Registry::HKEY_USERSDefaultProfileSoftwarePoliciesMicrosoftWindowsStoreRemoveWindowsStore changed from 0 to 1
    Registry::HKEY_USERSS-1-5-21-3870645062-3653562310-3850680542-1001SoftwarePoliciesMicrosoftWindowsStoreRemoveWindowsStore changed from 0 to 1
    Registry::HKEY_USERSS-1-5-21-3870645062-3653562310-3850680542-1002SoftwarePoliciesMicrosoftWindowsStoreRemoveWindowsStore changed from 0 to 1

PARAMETER: -ExcludeUsers "Test1,Test2"
    A comma seperated list of users to exclude. Please note newly created users will not have the windows store disabled.
.EXAMPLE
    -ExcludeUsers "Test1,Test2"

    WARNING: The Following Users and newly created users will not have the windows store disabled. Test1 Test2
    Registry::HKEY_USERSS-1-5-21-3870645062-3653562310-3850680542-1002SoftwarePoliciesMicrosoftWindowsStoreRemoveWindowsStore changed from 0 to 1
    WARNING: Creating AppLocker rule for user or group "tuser"...

PARAMETER: -ExistingUsersOnly
    This will disable the Windows store for existing users only.
.EXAMPLE
    -ExistingUsersOnly

    WARNING: Only existing users will have the windows store disabled!
    Set Registry::HKEY_USERSS-1-5-21-3870645062-3653562310-3850680542-1001SoftwarePoliciesMicrosoftWindowsStoreRemoveWindowsStore to 1
    WARNING: Creating AppLocker rule for user or group "kbohlander"...
    Set Registry::HKEY_USERSS-1-5-21-3870645062-3653562310-3850680542-1002SoftwarePoliciesMicrosoftWindowsStoreRemoveWindowsStore to 1
    WARNING: Creating AppLocker rule for user or group "tuser"...
.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 (
    [Parameter()]
    [String[]]$ExcludeUsers,
    [Parameter()]
    [Switch]$ExistingUsersOnly
)

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"
                $DefaultProfile | Where-Object { $ExcludedUsers -notcontains $_.UserName }
            }
        }

        $UserProfiles | Where-Object { $ExcludedUsers -notcontains $_.UserName }
    }

    function New-WindowStoreBlock {
        param(
            [Parameter()]
            [String]$User
        )

        Write-Warning "Creating AppLocker rule for user or group `"$User`"..."
        [xml]$AppLockerTemplate = Get-AppXPackage -AllUsers -Name "Microsoft.WindowsStore" | Get-AppLockerFileInformation | New-AppLockerPolicy -User "$User" -Optimize -Xml
        $AppLockerTemplate.AppLockerPolicy.RuleCollection.EnforcementMode = "Enabled"
        $AppLockerTemplate.AppLockerPolicy.RuleCollection.FilePublisherRule.Action = "Deny"
        $AppLockerTemplate.AppLockerPolicy.RuleCollection.FilePublisherRule.Conditions.FilePublisherCondition.BinaryVersionRange.LowSection = "*"
        $AppLockerTemplate.Save("$env:TEMPapplocker.xml")
        Set-AppLockerPolicy -XmlPolicy "$env:TEMPapplocker.xml" -Merge
        Remove-Item "$env:TEMPapplocker.xml"
    }
}
process {
    if ($env:ExistingUsersOnly) { $ExistingUsersOnly = $env:ExistingUsersOnly }
    # This registry key only works sometimes. It's worth setting if its an older windows build or has an older version of the store installed.
    $Path = "SoftwarePoliciesMicrosoftWindowsStore"
    $Name = "RemoveWindowsStore"
    $Value = 1
    
    # Get each user profile SID and Path to the profile. If there are any exclusions we'll have to take them into account.
    if ($ExcludeUsers -or $env:ExcludeUsers -or $ExistingUsersOnly) {
        if ($env:ExcludeUsers) {
            $ToBeExcluded = @()
            $ToBeExcluded += $env:ExcludeUsers.split(",").trim()
        }

        if ($ExcludeUsers) {
            $ToBeExcluded = @()
            $ToBeExcluded += $ExcludeUsers.split(",").trim()
        }

        if ($ToBeExcluded) { 
            Write-Warning "The Following Users and newly created users will not have the windows store disabled. $ToBeExcluded"
            $UserProfiles = Get-UserHives -ExcludedUsers $ToBeExcluded 
        }
        elseif ($ExistingUsersOnly) { 
            Write-Warning "Only existing users will have the windows store disabled!"
            $UserProfiles = Get-UserHives 
        }
    }
    else {
        $UserProfiles = Get-UserHives -IncludeDefault
    }

    [xml]$AppLockerXML = '<AppLockerPolicy Version="1"><RuleCollection Type="Appx" EnforcementMode="Enabled"><FilePublisherRule Id="a9e18c21-ff8f-43cf-b9fc-db40eed693ba" Name="(Default Rule) All signed packaged apps" Description="Allows members of the Everyone group to run packaged apps that are signed." UserOrGroupSid="S-1-1-0" Action="Allow"><Conditions><FilePublisherCondition PublisherName="*" ProductName="*" BinaryName="*"><BinaryVersionRange LowSection="0.0.0.0" HighSection="*" /></FilePublisherCondition></Conditions></FilePublisherRule></RuleCollection></AppLockerPolicy>'
    $AppLockerXML.Save("$env:TEMPapplocker.xml")
    Set-AppLockerPolicy -XmlPolicy "$env:TEMPapplocker.xml" -Merge
    Remove-Item "$env:TEMPapplocker.xml"

    if (!$ToBeExcluded -and !$ExistingUsersOnly) {
        New-WindowStoreBlock -User "Interactive"
    }

    $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

        # This will be our applocker policy we'll need to tweak it prior to running it
        if ($UserProfile.SID -notlike "DefaultProfile") {
            if ($ToBeExcluded -or $ExistingUsersOnly) {
                New-WindowStoreBlock -User "$($UserProfile.UserName)"
            }
        }

        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-Process -FilePath "cmd.exe" -ArgumentList "/C sc config `"AppIDSvc`" start=auto & net start `"AppIDSvc`"" -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 {}

 

Zugriff auf über 300 Skripte im NinjaOne Dojo

Zugang erhalten

Hauptmerkmale des Skripts

Prüfung auf erhöhte Berechtigungen

Bevor das Skript Änderungen vornehmen kann, prüft es, ob es mit Administratorrechten ausgeführt wird. Dies ist wichtig, um Änderungen an Systemeinstellungen und Benutzerkonten vorzunehmen.

Flexibilität bei Benutzerausschlüssen

Wenn Sie die Einstellungen nicht auf alle Benutzer:innen anwenden möchten, haben Sie die Möglichkeit, eine durch Komma getrennte Liste von Benutzer:innen anzugeben, die ausgeschlossen werden sollen.

Option nur für bestehende Benutzer:innen

Wenn Sie es vorziehen, dass neu erstellte Konten nicht betroffen sind, gibt es auch dafür einen Parameter.

Manipulation der Registrierung

Das Skript nutzt die Windows-Registrierung, um Richtlinienänderungen durchzusetzen, und stellt sicher, dass diese tief verwurzelt sind und Systemneustarts überstehen.

AppLocker-Integration

Das Skript geht über einfache Registrierungsänderungen hinaus, indem es auch eine AppLocker-Regel erstellt, um den Windows Store zu blockieren, was eine zusätzliche Sicherheitsebene darstellt.

Wie MSPs davon profitieren können

Kundenspezifische Anpassung

Mit der Option, bestimmte Benutzer:innen auszuschließen, können MSPs das Verhalten des Skripts an die individuellen Bedürfnisse jedes Kunden anpassen.

Skalierbarkeit

Egal, ob Sie ein kleines Unternehmensnetzwerk oder ein multinationales Unternehmen verwalten, dieses Skript lässt sich dank seiner Automatisierungsfunktionen mühelos skalieren.

Einhaltung der Vorschriften

In vielen Branchen gibt es strenge Compliance-Richtlinien, die die Nutzung von Anwendungen einschränken. Dieses Skript hilft bei der Einhaltung dieser Vorschriften, indem es den Zugriff auf nicht autorisierte Anwendungen aus dem Windows Store blockiert.

Mehrwert-Service

MSPs können dies als Teil ihres Sicherheitspakets anbieten und so ihren Service für potenzielle Kunden attraktiver machen.

Zusammenfassung

Sicherheit und Compliance sind zwei Seiten derselben Medaille im IT-Management. Dieses PowerShell-Skript erleichtert beides, indem es den Prozess der Deaktivierung des Windows-Speichers für mehrere Benutzerkonten automatisiert, mit anpassbaren Optionen für verschiedene Anwendungsfälle. Sowohl IT-Fachleute als auch MSPs können durch die Integration dieses Skripts in ihre regulären Arbeitsabläufe erhebliche Zeiteinsparungen, verbesserte Sicherheit und eine optimierte Verwaltung erzielen.

Nächste Schritte

Der Aufbau eines effizienten und effektiven IT-Teams erfordert eine zentralisierte Lösung, die als vereintes Tool für die Bereitstellung von Dienstleistungen fungiert. NinjaOne ermöglicht es IT-Teams, all ihre Geräte zu überwachen, verwalten, sichern und zu unterstützen, unabhängig von ihrem Ort und komplexer Infrastruktur vor Ort.

Erfahren Sie mehr über NinjaOne Endpoint Management schauen Sie sich eine Live-Tour an oder starten Sie Ihre kostenlose Testversion der NinjaOne Plattform.

Kategorien:

Das könnte Sie auch interessieren

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our 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 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).