Установить ключи реестра как системные для пользователей под hkey users

The Disable Local Admin Tools PowerShell Script

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

Access over 300+ scripts in the NinjaOne Dojo

:/>  BCDEDIT: редактирование загрузчика Windows | вебисторий

How the Script Works

This PowerShell script performs three important validations:

  1. Checks if the script is being run with administrative privileges.
  2. Loads the registry keys for each user profile, except for those explicitly excluded.
  3. Modifies or sets registry keys to disable the selected administrative tools.

Why IT Professionals and MSPs Should Care

Centralized Control

Security

Versatility

Automation and Scalability

For MSPs, the script can be integrated into automated deployment processes, making it scalable for large networks. Imagine the convenience of rolling this out to thousands of machines with just a few clicks.

How to Deploy

Final Thoughts

  1.   

    powerShell – registry help


    I was assigned to take all my scripts that are in batch files and convert them to PowerShell. I’m really confused on how you plug things into the registry it’s different from the batch file.

    So, here’s my dilemma, I am trying to figure out how to add this to the registry using PowerShell.

    reg add "HKU\Default\AppEvents\Schemes" /VE /T REG_SZ /F /D ".None"

    /VE :Compare or SET the empty value name (default)

    This is what I came up in for the PowerShell

    Set-ItemProperty -Path "HKU\Default\AppEvents\Schemes" -Name "(Default)" -Value ".None" -PropertyType "String"

    This doesn’t seem to work, and I can’t figure out how to set .None to the default name


  2.   


    Use chatgpt or simliar and just as it to convert cmd to powershell in seconds

    Set-ItemProperty -Path “HKU\Default\AppEvents\Schemes” -Name “(Default)” -Value “.None”


  3.   


    I’m just confused on how to tell it to use the default name and replace the value and not create a new value underneath scheme.


  4.   


    I was assigned to take all my scripts that are in batch files and convert them to PowerShell. I’m really confused on how you plug things into the registry it’s different from the batch file.

    There are no batch file commands for working with the registry. You have been using the external program Reg.exe all along and can continue to do so in PowerShell. The changes will be trivial if you convert your batch files to PowerShell and continue to use Reg.exe for all of your registry settings. Were you specifically instructed to no longer use Reg.exe?


  5.   


    ChatGPT is still a few years from replacing actual developers.

    There’s several problems you need to overcome, and they’re not obvious if you never done this.

    2. Set-ItemProperty assumes the path hierarchy for your nested key exists, and if it doesn’t — oops.

    3. You need to check, and create the path first.

    4. If you expect to use the new reg values immediately afterwards — don’t. There’s a common race condition where the hive doesn’t get flushed to disk. The preferred workaround is issue a garbage collection call (don’t ask me why), and then wait for a second. Now you probably don’t need it here, but might as well learn this lesson.

    $Path = "HKU:\.Default\AppEvents\Schemes"
    $Name = "(Default)"
    $Value = ".None"
    $null = New-PSDrive HKU Registry HKEY_USERS
    if (!(Test-Path($Path))) { New-Item $Path -Force }
    Set-ItemProperty -Path $Path -Name $Name -Value $Value -Force
    Get-ItemProperty -Path $Path -Name $Name
    [System.GC]::Collect()

    powerShell - registry help-image.png


  6.   


    The preferred workaround is issue a garbage collection call (don’t ask me why), and then wait for a second.

    Interesting, thanks for posting.

    Have I understood correctly that you are suggesting

    [System.GC]::Collect()
    Sleep -s 1

    before going on to use the new Registry entries?
    PS Start-Sleep – MSLearn

    All the best,
    Denis


  7.   


    Normally most users operate on HKCU, which is you in the active session. Your hive is always mounted during this time. But if you had to mount an offline user, usually you run “reg load HKLM\TEMP User.dat”. Then do your work, before unloading it with “reg unload”.

    That’s where the garbage collection comes in. If you wait a few seconds after the reg updates, it should cycle thru. But if you were in a hurry and wanted to force commit the changes to disk, you need to guarantee everything is flushed.

    I would imagine making a handful of changes isn’t triggering this condition. But consider what happens if you made a ton of updates. The hive structure isn’t optimized for performance, so lag has to be accounted for.


  8.   


    Thank you, @garlin, for helping me with this I sat around and looked and looked at different people’s comments on this issue on Google and nothing ever seemed to work until now. Thank you for taking the time and answering my question. If I come across another issue, can I PM you with the question.


The problem with logged-on users

Here’s an example of this conflict.

PS-Blog-Registry-HKU-example

PS-Blog-Registry-Cannot-load-ntuser.dat

How to identify all users and their SIDs in Windows

  1. Launch Registry Editor (regedit.exe).

  2. Navigate to this registry key: HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\

This location has a list of all the SIDs for the machine as well as some other properties. We’re interested in the SIDs that start with S-1-5-21. Notice that you see the two SIDs from an earlier screenshot:

PS-Blog-Registry-ProfileList-example

With this information, we can use regular expressions and calculated properties to select some great information with PowerShell. We’ll use the Get-ItemProperty cmdlet to get that information from the registry.

Comparing SIDs to usernames in PowerShell.

Comparing profile SIDs to logged-on user SIDs

PowerShell script to modify the registry for all users

Modifying the registry for all users full script results.

Modify the registry at your own risk

Use this information with a healthy dose of caution. Modifying the registry is risky and can quickly turn a good day into a bad one. Even good reasons to modify the registry aren’t good enough. Be responsible and thoroughly test your scripts in a safe environment before running them anywhere near your production environment. We cannot be held responsible for any issues that you may encounter.

Brock Bingham candid headshot

Born in the ’80s and raised by his NES, Brock quickly fell in love with everything tech. With over 15 years of IT experience, Brock now enjoys the life of luxury as a renowned tech blogger and receiver of many Dundie Awards. In his free time, Brock enjoys adventuring with his wife, kids, and dogs, while dreaming of retirement.

i would appreciate your swarm intelligence again.

I knew there was no drive mapped by default but this did worked properly fine in tests.
After deploying the script via intune as system i got a error message while testing the path which was something like: No Provider found

What i can see is that the PSDrive is successfuly mapped.
Sadly a got another error. Different message same meaning:

The drive was not found. A drive with that name is not available.

For some additional informations here are some snippets of the code an the error in the log (in german cause the os language is german):

 $HiveHash = @{ "HKEY_CLASSES_ROOT" = "HKLM:\SOFTWARE\Classes" "HKEY_CURRENT_USER" = "HKCU:" "HKEY_LOCAL_MACHINE" = "HKLM:" "HKEY_USERS" = "HKU:" "HKEY_CURRENT_CONFIG" = "HKCC:" } # Local User Profiles $AllLocalUsers = Get-WmiObject Win32_userprofile | where { $_.localpath -like ($env:SystemDrive + "\Users*" ) } # Build User SID Array [System.Collections.ArrayList]$AllLocalUsersSIDs = @() $AllLocalUsersSIDs += $AllLocalUsers.SID # Add also Default Profile $AllLocalUsersSIDs += ".DEFAULT" Add-RegKeyToArray -Key 'HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced' -ValueName 'HideFileExt' -Value '0' -ValueType 'REG_DWORD' # Operation Key # Define Key Variables If( $RunAllUsers ) { # Hive $KeyHivePS = "HKU:" $KeyHivePSWithoutColon = $KeyHivePS.TrimEnd(":") $KeyHive = ( $HiveHash.GetEnumerator() | ? { $_.Value -match $KeyHivePS } ).Name # Key # Timed Key Path to add Userprofil Part $KeyPathAllUsers = $Key.TrimStart("HKEY_CURRENT_USER") } Else { # Hive $KeyHive = $Key.split('\')[0] $KeyHivePS = $HiveHash.$KeyHive $KeyHivePSWithoutColon = $KeyHivePS.TrimEnd(":") # Key $Key = $Key -replace $KeyHive,$KeyHivePS $KeyWithoutSingleQuotes = $Key $Key = "'" + $Key + "'" } # Mount Registry PSDrive If( ! ( Get-PSDrive $KeyHivePSWithoutColon -ErrorAction SilentlyContinue ) ) { New-PSDrive -Name $KeyHivePSWithoutColon -PSProvider Registry -Root $KeyHive | Out-Null Log $KeyHivePSWithoutColon 3 Log $KeyHive 3 Log ( $( Get-PSDrive -Name $KeyHivePSWithoutColon | Out-String ) ) 3 } # Operate If( $Action -eq "Remove" ) { ... } ElseIf( $Action -eq "Create" ) { # Check existing If( $RunAllUsers ) { ForEach( $LocaluserSID in $AllLocalUsersSIDs ) { # In case we got a SID without a Profil If( Test-Path -Literalpath ( $KeyHivePS + "\" + $LocaluserSID ) ) { # Build Key Path with User SID $Key = ( $KeyHivePS + "\" + $LocaluserSID + $KeyPathAllUsers ) $KeyWithoutSingleQuotes = $Key $Key = "'" + $Key + "'" # Add KeyPath to Array for Value Operation $KeysArray += $Key # Output Log ( "Path: {0}" -f $KeyWithoutSingleQuotes ) 3 Set-PSBreakpoint -Line 1195 -Script $PSCOMMANDPATH # Checking If( Test-Path -LiteralPath $Key ) { Log ( "Exists: True" ) 3 } Else { Log ( "Exists: False" ) 3 # RemediationMode If( $RemediationMode -eq "remediate" ) { # Create New-Item -Path $Key -Force | Out-Null # Check Create If( Test-Path -LiteralPath $Key ) { Log ( "Created: True" ) 3 } Else 

And here the part from the log:
enter image description here

And for the Quesition in the Comment: The “Exits: False” is also wrong because its a standard microsoft key which has to be there. New-Item uses just the same Path $Key and generate the error. So the Problem is the HKU: Drive within. Changed the code for you.

Well it seems thats nothing new: File path with quotation mark issue of Powershell

I have created a powershell script to activate a specific screensaver, password enable it and set the idle timeout value, but it does not work when I try to run it from the PulseWay Web interface.

I have also tried it from a batch script, but it does not work either.

Both scripts work fine when running them directly from the local computer.

#Values to customize
$ScreenSaveActive = 1 #set to 1 if you want the screensaver enabled, 0 to disable
$TimeOutValue = 60 # number of idle seconds before screensaver gets active
$ScreenSaverFile = “C:\Windows\system32\mystify.scr” # full path to screensaver file
$ScreenSaverIsSecure = 1 # set to 1 if you need a password to get out of screensaver, a.k.a. unlocking the pc

I have also tried this from batch script, but it does not work either.