Se Demo×
×

Se NinjaOne i aktion!

Genom att skicka detta formulär accepterar jag NinjaOne:s integritetspolicy.

Hur man inaktiverar lokala adminverktyg i Windows [PowerShell-skript]

IT-proffs och IT-partners (MSP): Om du har fått i uppgift att upprätthålla nätverkssäkerhet och administrativ åtkomst vet du att det ofta är lättare sagt än gjort. En viktig aspekt av detta är hanteringen av lokala administratörsverktyg som användarna inte bör ha fri tillgång till. Detta leder oss till en fråga som ofta ställs: Hur inaktiverar jag lokala administratörsverktyg i stor skala?

Vi har ett omfattande PowerShell-skript som gör att du selektivt kan inaktivera administratörsverktyg i en Windows-miljö.

PowerShell-skriptet Inaktivera lokala administratörsverktyg

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

 

Få tillgång till över 300+ skript i NinjaOne Dojo

Få tillgång till

Hur manuset fungerar

Skriptet vi diskuterar är skrivet i PowerShell och är utformat för att inaktivera specifika administrativa verktyg på lokala maskiner. Den har optimerats för att fungera med PowerShell 5.1 och har olika valbara alternativ som Kommandotolken, Kontrollpanelen, Microsoft Management Console (MMC), Registerredigeraren, Kör kommandofönster och Aktivitetshanteraren. Du kan antingen inaktivera alla dessa verktyg eller välja från en kommaseparerad lista för att inaktivera endast specifika verktyg.

Dessutom ger skriptet möjlighet att utesluta vissa användarprofiler från denna åtgärd. Om du behöver se till att vissa användare behåller sina administratörsfunktioner kan du enkelt göra det.

Detta PowerShell-skript utför tre viktiga valideringar:

  1. Kontrollerar om skriptet körs med administratörsbehörighet.
  2. Läser in registernycklarna för varje användarprofil, med undantag för de som uttryckligen har undantagits.
  3. Ändrar eller ställer in registernycklar för att inaktivera de valda administrativa verktygen.

Det handlar inte bara om inaktivering, utan även om kontroll och specificitet, vilket gör detta skript mycket mångsidigt för IT-administratörer och IT-partners.

Varför IT-proffs och IT-partners bör bry sig

Centraliserad kontroll

Med hjälp av detta PowerShell-skript kan IT-personal inaktivera lokala administrationsverktyg på ett centraliserat sätt, vilket avsevärt minskar den tid det skulle ta att göra detta manuellt för varje användare.

Säkerhet

Inaktivering av dessa verktyg förbättrar säkerheten genom att begränsa användarnas möjligheter att göra ändringar på systemnivå. Detta är särskilt användbart i miljöer där man vill minimera potentiella säkerhetsrisker inifrån.

Mångsidighet

Skriptets förmåga att selektivt inaktivera verktyg och utesluta specifika användare ger det en flexibilitet som är skräddarsydd för olika IT-miljöer. Det är inte en storlek som passar alla, det är en storlek som passar hur du vill ha det.

Automatisering och skalbarhet

För IT-partners kan skriptet integreras i automatiserade driftsättningsprocesser, vilket gör det skalbart för stora nätverk. Föreställ dig hur enkelt det är att rulla ut detta till tusentals maskiner med bara några få klick.

Hur man distribuerar

Ladda bara ner skriptet Disable-LocalAdminTools.ps1 och kör det via PowerShell på måldatorerna. Skriptet stöder olika kommandoradsalternativ för att finjustera vad du vill inaktivera.

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

Avslutande tankar

Oavsett om du är en IT-specialist som letar efter en lösning för att inaktivera lokala administratörsverktyg eller en IT-partners som letar efter ett enkelt implementerbart skript för inaktivering av administratörsverktyg, ger detta PowerShell-skript en robust, flexibel och effektiv lösning. Det tar komplexitet och gör det enkelt, vilket ger dig mer kontroll över nätverkets säkerhetsinställningar.

Håll dig steget före genom att använda denna effektiva och målinriktade metod för administrativ åtkomst. Lycka till med skrivarbetet!

Nästa steg

För att bygga upp ett effektivt och handlingskraftigt IT-team krävs en centraliserad lösning som fungerar som ett centralt redskap för att leverera IT-tjänster. NinjaOne gör det möjligt för IT-teams att övervaka, hantera, säkra och stödja alla sina enheter, oavsett var de befinner sig, utan behovet av en komplex infrastruktur på plats.

Lär dig mer om NinjaOne endpoint-hantering, ta en live tour, eller starta en gratis provperiod av NinjaOne.

Du kanske även gillar

NinjaOne Villkor och bestämmelser

Genom att klicka på knappen ”Jag accepterar” nedan anger du att du accepterar följande juridiska villkor samt våra användarvillkor:

  • Äganderätt: NinjaOne äger och kommer att fortsätta att äga alla rättigheter, titlar och intressen i och till manuset (inklusive upphovsrätten). NinjaOne ger dig en begränsad licens att använda skriptet i enlighet med dessa juridiska villkor.
  • Begränsning av användning: Du får endast använda skriptet för dina legitima personliga eller interna affärssyften, och du får inte dela skriptet med någon annan part.
  • Republikbildning Förbud: Du får under inga omständigheter återpublicera skriptet i något skriptbibliotek som tillhör eller kontrolleras av någon annan programvaruleverantör.
  • Friskrivning från garantiansvar: Skriptet tillhandahålls ”i befintligt skick” och ”som tillgängligt”, utan garanti av något slag. NinjaOne ger inga löften eller garantier om att skriptet kommer att vara fritt från defekter eller att det kommer att uppfylla dina specifika behov eller förväntningar.
  • Antagande av risk: Din användning av skriptet sker på egen risk. Du bekräftar att det finns vissa inneboende risker med att använda skriptet, och du förstår och tar på dig var och en av dessa risker.
  • Avstående och befrielse: Du kommer inte att hålla NinjaOne ansvarig för några negativa eller oavsiktliga konsekvenser till följd av din användning av skriptet, och du avstår från alla juridiska eller skäliga rättigheter eller rättsmedel som du kan ha mot NinjaOne i samband med din användning av skriptet.
  • EULA: Om du är en NinjaOne-kund omfattas din användning av skriptet av det licensavtal för slutanvändare som gäller för dig (EULA).