Come disabilitare gli strumenti di amministrazione locale in Windows [script PowerShell]

Attenzione, professionista IT e fornitore di servizi gestiti (MSP): Se sei stato incaricato di mantenere la sicurezza della rete e l’accesso amministrativo, devi sapere che spesso è più facile a dirsi che a farsi. Un aspetto fondamentale è la gestione degli strumenti di amministrazione locale a cui gli utenti non dovrebbero avere libero accesso. Questo ci porta a una domanda che viene spesso posta: Come puoi disabilitare gli strumenti di amministrazione locale su larga scala? 

Abbiamo uno script PowerShell completo che consente di disabilitare gli strumenti di amministrazione locale in modo selettivo in ambiente Windows. 

Lo script PowerShell per disabilitare gli strumenti di amministrazione locale

#Requires -Version 5.1

<#
.SYNOPSIS
    This will disable the selected administrator tools depending on your selection (Defaults to all). Can be given a comma seperated list/string of tools to be disabled.
    Can also be given a comma seperated list of users to exclude from this action. Full Options: "All", "Cmd", "ControlPanel", "MMC", "RegistryEditor", "Run", "TaskMgr"
.DESCRIPTION
    This will disable the selected administrator tools. The options are "All", the command prompt, the control panel, the microsoft management console,
    the registry editor, the run command window and task manager. You can give it a comma seperated list of items if you want to disable some but not all.
    Exit 1 is usually an indicator of bad input but can also mean editing the registry is blocked.
.EXAMPLE
    PS C:> .Disable-LocalAdminTools.ps1 -Tools "MMC,Cmd,TaskMgr,RegistryEditor"
    Disabling MMC...
    Set Registry::HKEY_USERSDefaultProfileSoftwarePoliciesMicrosoftMMCRestrictToPermittedSnapins to...
    Disabling Cmd...
    Set Registry::HKEY_USERSDefaultProfileSoftwarePoliciesMicrosoftWindowsDisableCMD to...
    Disabling TaskMgr...
    Set Registry::HKEY_USERSDefaultProfileSoftwareMicrosoftWindowsCurrentVersionPoliciesSystemDisableTaskMgr to...
    Disabling RegistryEditor...
    Set Registry::HKEY_USERSDefaultProfileSoftwareMicrosoftWindowsCurrentVersionPoliciesSystemDisableRegistryTools to...
.OUTPUTS
    None
.NOTES
    General notes: Will set the regkeys for users created after this script is ran.
    Release Notes:
    Initial Release
    (c) 2023 NinjaOne
    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/it/condizioni-utilizzo
    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]$Tools = "All",
    [Parameter()]
    [String]$ExcludedUsers
    <#
        ## ParameterName Requirement DefaultValue Type Options Description ##
        All Optional true CHECKBOX All Admin Tools
        Cmd Optional false CHECKBOX Command Prompt
        ControlPanel Optional false CHECKBOX Control Panel
        MMC Optional false CHECKBOX Microsoft Managment Console
        RegistryEditor Optional false CHECKBOX The Registry Editor
        Run Optional false CHECKBOX Run Command Window
        TaskMgr Optional false CHECKBOX Task Manager
        ExcludedUsers Optional none TEXT Comma seperated list of users you would like to exclude.
    #>
)

begin {
    # Lets double check that this script is being run appropriately
    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 "[Error] 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
            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)"
        }
        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)"
        }
    }

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

    function Set-Tool {
        [CmdletBinding()]
        param(
            [Parameter()]
            [ValidateSet("All", "Cmd", "ControlPanel", "MMC", "RegistryEditor", "Run", "TaskMgr")]
            [string]$Tool,
            [string]$key
        )
        process {
            # Each option has a different registry key to change. Since this function only supports 1 item at a time I can check which option and set the regkey individually.
            Write-Host "Disabling $Tool..."
            switch ($Tool) {
                "Cmd" { Set-HKProperty -Path $keySoftwarePoliciesMicrosoftWindowsSystem -Name DisableCMD -Value 1 }
                "ControlPanel" { Set-HKProperty -Path $keySoftwareMicrosoftWindowsCurrentVersionPoliciesExplorer -Name NoControlPanel -Value 1 }
                "MMC" { Set-HKProperty -Path $keySoftwarePoliciesMicrosoftMMC -Name RestrictToPermittedSnapins -Value 1 }
                "RegistryEditor" { Set-HKProperty -Path $keySoftwareMicrosoftWindowsCurrentVersionPoliciesSystem -Name DisableRegistryTools -Value 1 }
                "Run" { Set-HKProperty -Path $keySoftwareMicrosoftWindowsCurrentVersionPoliciesExplorer -Name NoRun -Value 1 }
                "TaskMgr" { Set-HKProperty -Path $keySoftwareMicrosoftWindowsCurrentVersionPoliciesSystem -Name DisableTaskMgr -Value 1 }
                "All" {
                    Set-HKProperty -Path $keySoftwarePoliciesMicrosoftWindowsSystem -Name DisableCMD -Value 1
                    Set-HKProperty -Path $keySoftwareMicrosoftWindowsCurrentVersionPoliciesSystem -Name NoDispCPL -Value 1
                    Set-HKProperty -Path $keySoftwarePoliciesMicrosoftMMC -Name RestrictToPermittedSnapins -Value 1
                    Set-HKProperty -Path $keySoftwareMicrosoftWindowsCurrentVersionPoliciesSystem -Name DisableRegistryTools -Value 1
                    Set-HKProperty -Path $keySoftwareMicrosoftWindowsCurrentVersionPoliciesExplorer -Name NoRun -Value 1
                    Set-HKProperty -Path $keySoftwareMicrosoftWindowsCurrentVersionPoliciesSystem -Name DisableTaskMgr -Value 1
                }
            }
        }
    }
}
process {

    # Get each user profile SID and Path to the profile. If there are any exclusions we'll have to take them into account.
    if($ExcludedUsers -or $env:ExcludedUsers){
        if($env:ExcludedUsers){
            $ToBeExcluded = @()
            $ToBeExcluded += $env:ExcludedUsers.split(",").trim()
            Write-Warning "The Following Users will not have your selected tools disabled. $ToBeExcluded"
        }else{
            $ToBeExcluded = @()
            $ToBeExcluded += $ExcludedUsers.split(",").trim()
            Write-Warning "The Following Users will not have your selected tools disabled. $ToBeExcluded"
        }
        $UserProfiles = Get-UserHives -IncludeDefault -ExcludedUsers $ToBeExcluded
    }else{
        $UserProfiles = Get-UserHives -IncludeDefault
    }

    # Loop through each profile on the machine
    Foreach ($UserProfile in $UserProfiles) {
        # Load each user's registry hive if not already loaded. Backticked "UserProfile.UserHive" so that it accounts for spaces in the username.
        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
        }
        # The path is different for each individual user. This is the base path.
        $key = "Registry::HKEY_USERS$($UserProfile.SID)"

        # List of checkbox items
        $CheckboxItems = "Cmd", "ControlPanel", "MMC", "RegistryEditor", "Run", "TaskMgr"
        # Checkboxes come in as environmental variables. This'll grab the ones that were selected (if any)
        $EnvItems = Get-ChildItem env:* | Where-Object { $CheckboxItems -contains $_.Name }

        # This will grab the tool selections from the parameter field. Since it comes in as a string we'll have to split it up.
        $Tool = $Tools.split(",").trim()

        # If the checkbox for all was selected I can just run the function once instead of running it repeatedly for the same thing.
        if ($env:All) {
            Set-Tool -Tool "All" -Key $key
        }elseif ($EnvItems) {
            # If checkboxes were used we should just use those.
            $EnvItems | ForEach-Object { Set-Tool -Tool $_.Name -Key $key }
        }else {
            $Tool | ForEach-Object { Set-Tool -Tool $_ -Key $key }
        }

        # Unload NTuser.dat for user's we loaded previously.
        If ($ProfileWasLoaded -eq $false) {
            [gc]::Collect()
            Start-Sleep -Seconds 1
            Start-Process -FilePath "cmd.exe" -ArgumentList "/C reg.exe UNLOAD HKU$($UserProfile.SID)" -Wait -WindowStyle Hidden | Out-Null
        }
    }
    
}
end {
    
}

|

#Requires -Version 5.1

<#
.SYNOPSIS
    This will disable the selected administrator tools depending on your selection (Defaults to all). Can be given a comma separated list of users to exclude from this action.
.DESCRIPTION
    This will disable the selected administrator tools. The options are "All", the command prompt, the control panel, the microsoft management console,
    the registry editor, the run command window and task manager. You can give it a comma separated list of items if you want to disable some but not all.
    Exit 1 is usually an indicator of bad input but can also mean editing the registry is blocked.
.EXAMPLE
    PS C:> .Disable-LocalAdminTools.ps1 -Tools "MMC,Cmd,TaskMgr,RegistryEditor"
    Disabling MMC...
    Set Registry::HKEY_USERSDefaultProfileSoftwarePoliciesMicrosoftMMCRestrictToPermittedSnapins to...
    Disabling Cmd...
    Set Registry::HKEY_USERSDefaultProfileSoftwarePoliciesMicrosoftWindowsDisableCMD to...
    Disabling TaskMgr...
    Set Registry::HKEY_USERSDefaultProfileSoftwareMicrosoftWindowsCurrentVersionPoliciesSystemDisableTaskMgr to...
    Disabling RegistryEditor...
    Set Registry::HKEY_USERSDefaultProfileSoftwareMicrosoftWindowsCurrentVersionPoliciesSystemDisableRegistryTools to...
.OUTPUTS
    None
.NOTES
    Minimum Supported OS: Windows 10, Windows Server 2016+
    Release Notes: Renamed script and added Script Variable support
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]$Tools = "All",
    [Parameter()]
    [String]$ExcludedUsers
)

begin {
    
    if ($env:excludeUsers -and $env:excludeUsers -notlike "null") { $ExcludedUsers = $env:excludeUsers }
    
    # Lets double check that this script is being run appropriately
    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 "[Error] 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
            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)"
        }
        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)"
        }
    }

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

    function Set-Tool {
        [CmdletBinding()]
        param(
            [Parameter()]
            [ValidateSet("All", "Cmd", "ControlPanel", "theControlPanel", "MMC", "RegistryEditor", "theRegistryEditor", "Run", "TaskMgr", "taskManager")]
            [string]$Tool,
            [string]$key
        )
        process {
            # Each option has a different registry key to change. Since this function only supports 1 item at a time I can check which option and set the regkey individually.
            Write-Host "Disabling $Tool..."
            switch ($Tool) {
                "Cmd" { Set-HKProperty -Path $keySoftwarePoliciesMicrosoftWindowsSystem -Name DisableCMD -Value 1 }
                "ControlPanel" { Set-HKProperty -Path $keySoftwareMicrosoftWindowsCurrentVersionPoliciesExplorer -Name NoControlPanel -Value 1 }
                "theControlPanel" { Set-HKProperty -Path $keySoftwareMicrosoftWindowsCurrentVersionPoliciesExplorer -Name NoControlPanel -Value 1 }
                "MMC" { Set-HKProperty -Path $keySoftwarePoliciesMicrosoftMMC -Name RestrictToPermittedSnapins -Value 1 }
                "RegistryEditor" { Set-HKProperty -Path $keySoftwareMicrosoftWindowsCurrentVersionPoliciesSystem -Name DisableRegistryTools -Value 1 }
                "theRegistryEditor" { Set-HKProperty -Path $keySoftwareMicrosoftWindowsCurrentVersionPoliciesSystem -Name DisableRegistryTools -Value 1 }
                "Run" { Set-HKProperty -Path $keySoftwareMicrosoftWindowsCurrentVersionPoliciesExplorer -Name NoRun -Value 1 }
                "TaskMgr" { Set-HKProperty -Path $keySoftwareMicrosoftWindowsCurrentVersionPoliciesSystem -Name DisableTaskMgr -Value 1 }
                "taskManager" { Set-HKProperty -Path $keySoftwareMicrosoftWindowsCurrentVersionPoliciesSystem -Name DisableTaskMgr -Value 1 }
                "All" {
                    Set-HKProperty -Path $keySoftwarePoliciesMicrosoftWindowsSystem -Name DisableCMD -Value 1
                    Set-HKProperty -Path $keySoftwareMicrosoftWindowsCurrentVersionPoliciesSystem -Name NoDispCPL -Value 1
                    Set-HKProperty -Path $keySoftwarePoliciesMicrosoftMMC -Name RestrictToPermittedSnapins -Value 1
                    Set-HKProperty -Path $keySoftwareMicrosoftWindowsCurrentVersionPoliciesSystem -Name DisableRegistryTools -Value 1
                    Set-HKProperty -Path $keySoftwareMicrosoftWindowsCurrentVersionPoliciesExplorer -Name NoRun -Value 1
                    Set-HKProperty -Path $keySoftwareMicrosoftWindowsCurrentVersionPoliciesSystem -Name DisableTaskMgr -Value 1
                }
            }
        }
    }
}
process {

    # Get each user profile SID and Path to the profile. If there are any exclusions we'll have to take them into account.
    if ($ExcludedUsers) {
        $ToBeExcluded = New-Object System.Collections.Generic.List[string]
        $ExcludedUsers.split(",").trim() | ForEach-Object { if ($_) { $ToBeExcluded.Add($_) } }
        Write-Warning "The Following Users will not have your selected tools disabled. $ToBeExcluded"
        $UserProfiles = Get-UserHives -IncludeDefault -ExcludedUsers $ToBeExcluded
    }
    else {
        $UserProfiles = Get-UserHives -IncludeDefault
    }

    # Loop through each profile on the machine
    Foreach ($UserProfile in $UserProfiles) {
        # Load each user's registry hive if not already loaded. Backticked "UserProfile.UserHive" so that it accounts for spaces in the username.
        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
        }
        # The path is different for each individual user. This is the base path.
        $key = "Registry::HKEY_USERS$($UserProfile.SID)"

        # List of checkbox items
        $CheckboxItems = "cmd", "theControlPanel", "mmc", "theRegistryEditor", "run", "taskManager"
        # Checkboxes come in as environmental variables. This'll grab the ones that were selected (if any)
        $EnvItems = Get-ChildItem env:* | Where-Object { $CheckboxItems -contains $_.Name -and $_.Value -notlike "false" }

        # This will grab the tool selections from the parameter field. Since it comes in as a string we'll have to split it up.
        $Tool = $Tools.split(",").trim()

        # If the checkbox for all was selected I can just run the function once instead of running it repeatedly for the same thing.
        if ($env:allTools -and $env:allTools -notlike "false") {
            Set-Tool -Tool "All" -Key $key
        }
        elseif ($EnvItems) {
            # If checkboxes were used we should just use those.
            $EnvItems | ForEach-Object { Set-Tool -Tool $_.Name -Key $key }
        }
        else {
            $Tool | ForEach-Object { Set-Tool -Tool $_ -Key $key }
        }

        # Unload NTuser.dat for user's we loaded previously.
        If ($ProfileWasLoaded -eq $false) {
            [gc]::Collect()
            Start-Sleep -Seconds 1
            Start-Process -FilePath "cmd.exe" -ArgumentList "/C reg.exe UNLOAD HKU$($UserProfile.SID)" -Wait -WindowStyle Hidden | Out-Null
        }
    }
    
}
end {
    
    
    
}

 

Accedi a oltre 700 script nel Dojo di NinjaOne Ottieni l’accesso

Come funziona lo script

Lo script per disabilitare gli strumenti di amministrazione locale di cui parliamo è scritto in PowerShell ed è progettato per disabilitare strumenti amministrativi specifici su macchine locali. È stato ottimizzato per funzionare con PowerShell 5.1 e presenta varie opzioni selezionabili come Prompt dei comandi, Pannello di controllo, Microsoft Management Console (MMC), Editor del registro, Finestra dei comandi di esecuzione e Task Manager. È possibile disabilitare tutti gli strumenti di amministrazione locale o scegliere da un elenco separato da virgole di disabilitarne soltanto alcuni. 

Inoltre, lo script consente di escludere determinati profili utente da questa azione. Se hai bisogno che alcuni utenti mantengano le loro capacità di utilizzare gli strumenti di amministrazione locale, potrai fare in modo che questo avvenga facilmente. 

Questo script PowerShell esegue tre importanti convalide: 

  1. Controlla se lo script viene eseguito con privilegi amministrativi. 
  2. Carica le chiavi di registro per ogni profilo utente, fatta eccezione per quelle esplicitamente escluse. 
  3. Modifica o imposta le chiavi di registro per disabilitare gli strumenti di amministrazione locale selezionati. 

Non si tratta solo di disabilitazione, ma di controllo e specificità, il che rende questo script molto versatile per gli amministratori IT e gli MSP. 

Perché i professionisti IT e gli MSP dovrebbero interessarsene

Controllo centralizzato 

Utilizzando questo script PowerShell per disabilitare gli strumenti di amministrazione locale, i professionisti IT possono disabilitare gli strumenti di amministrazione locale in modo centralizzato, riducendo in modo significativo il tempo necessario per eseguire questa operazione manualmente per ogni utente. 

Sicurezza 

Disabilitare gli strumenti di amministrazione locale aumenta la sicurezza limitando la possibilità per gli utenti di apportare modifiche a livello di sistema. Questo è particolarmente utile negli ambienti in cui si desidera ridurre al minimo i potenziali rischi per la sicurezza che arrivano dall’interno. 

Versatilità 

La capacità dello script di disabilitare gli strumenti di amministrazione locale in modo selettivo e di escludere utenti specifici gli conferisce una flessibilità perfetta per diversi ambienti IT. Non si tratta di una soluzione valida per tutti, ma di una soluzione che può essere personalizzata secondo le necessità. 

Automazione e scalabilità 

Per gli MSP, lo script può essere integrato nei processi di distribuzione automatizzati e può essere reso così scalabile per reti di grandi dimensioni. Immagina la comodità di poterlo distribuire su migliaia di macchine con pochi clic. 

Come distribuirlo

È sufficiente scaricare lo script Disable-LocalAdminTools.ps1 ed eseguirlo tramite PowerShell sui computer di destinazione. Lo script supporta diverse opzioni da riga di comando per regolare con precisione quello che desideri disabilitare. 

PS C:> .Disable-LocalAdminTools.ps1 -Tools “MMC,Cmd,TaskMgr,RegistryEditor”

Considerazioni finali

Che tu sia un professionista IT alla ricerca di una soluzione per disabilitare gli strumenti di amministrazione locale o un MSP alla ricerca di uno script, facilmente implementabile, per disabilitare gli strumenti di amministrazione locale, questo script PowerShell ti offre una soluzione solida, flessibile ed efficiente. Una soluzione che trasforma la complessità in semplicità, offrendo un maggiore controllo sulle impostazioni di sicurezza della rete. 

Rimani all’avanguardia utilizzando questo approccio efficiente e mirato all’accesso amministrativo. Buon scripting! 

Passi successivi

La creazione di un team IT efficiente ed efficace richiede una soluzione centralizzata che funga da principale strumento per la fornitura di servizi. NinjaOne consente ai team IT di monitorare, gestire, proteggere e supportare tutti i dispositivi, ovunque essi si trovino, senza la necessità di una complessa infrastruttura locale.

Per saperne di più su NinjaOne Endpoint Management, fai un tour dal vivo, o inizia la tua prova gratuita della piattaforma NinjaOne.

Categorie:

Ti potrebbe interessare anche

Guarda una demo×
×

Guarda NinjaOne in azione!

Inviando questo modulo, accetto La politica sulla privacy di NinjaOne.

Termini e condizioni NinjaOne

Cliccando sul pulsante “Accetto” qui sotto, dichiari di accettare i seguenti termini legali e le nostre condizioni d’uso:

  • Diritti di proprietà: NinjaOne possiede e continuerà a possedere tutti i diritti, i titoli e gli interessi relativi allo script (compreso il copyright). NinjaOne ti concede una licenza limitata per l’utilizzo dello script in conformità con i presenti termini legali.
  • Limitazione d’uso: Puoi utilizzare lo script solo per legittimi scopi personali o aziendali interni e non puoi condividere lo script con altri soggetti.
  • Divieto di ripubblicazione: In nessun caso ti è consentito ripubblicare lo script in una libreria di script appartenente o sotto il controllo di un altro fornitore di software.
  • Esclusione di garanzia: Lo script viene fornito “così com’è” e “come disponibile”, senza garanzie di alcun tipo. NinjaOne non promette né garantisce che lo script sia privo di difetti o che soddisfi le tue esigenze o aspettative specifiche.
  • Assunzione del rischio: L’uso che farai dello script è da intendersi a tuo rischio. Riconosci che l’utilizzo dello script comporta alcuni rischi intrinseci, che comprendi e sei pronto ad assumerti.
  • Rinuncia e liberatoria: Non riterrai NinjaOne responsabile di eventuali conseguenze negative o indesiderate derivanti dall’uso dello script e rinuncerai a qualsiasi diritto legale o di equità e a qualsiasi rivalsa nei confronti di NinjaOne in relazione all’uso dello script.
  • EULA: Se sei un cliente NinjaOne, l’uso dello script è soggetto al Contratto di licenza con l’utente finale (EULA) applicabile.