Home > other >  Powershell - Unable to modify registry key ACL despite being the owner
Powershell - Unable to modify registry key ACL despite being the owner

Time:04-29

I'm trying to write a script that modifies a registry value. Before modifying it, I have to remove a 'Deny' permission rule to the current user, which is also the owner of the registry key and has full control permissions. Since current user is the owner and has full control, is able to modify the registry key permissions manually and remove the 'deny' rule. But so far I'm not able to do it with powershell since I always get an 'access denied' error. This is what I tried so far:

$currentuser = $env:UserDomain   "\"   $env:UserName
$regpath = "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.htm\UserChoice"
$acl = Get-Acl -path $regpath
$rule = New-Object System.Security.AccessControl.RegistryAccessRule($currentuser,"SetValue","Deny")
$Acl.RemoveAccessRuleAll($Rule)
$acl | Set-Acl -Path $regpath

What am I missing? Is there any possible way to do this with powershell? I don't want to use any third party. Thanks in advance for your help

CodePudding user response:

You cannot remove a new rule object. You must remove an existing rule object.

$DebugPreference = "Continue"

$currentuser = $env:UserDomain   "\"   $env:UserName
$regpath = "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer"
$acl = Get-Acl -path $regpath
$rule = $acl.Access | where {
    $_.IdentityReference -eq $currentuser `
    -and $_.IsInherited -eq $False `
    -and $_.RegistryRights -eq "SetValue" `
    -and $_.AccessControlType -eq "Deny"
}
if ($rule) {
    $acl.RemoveAccessRuleSpecific($rule)
    $acl | Set-Acl -Path $regpath
    Write-Debug 'Rule removed'
} else {
    Write-Debug 'No matching rule found'
}

CodePudding user response:

Thanks to the help of @Tomalak, I was able to delete the Deny rule with this code:

$key = [Microsoft.Win32.Registry]::CurrentUSer.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.htm\UserChoice",[Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree,[System.Security.AccessControl.RegistryRights]::ChangePermissions)
$acl = $key.GetAccessControl()
$currentuser = $env:UserDomain   "\"   $env:UserName
$rule = $acl.Access | where {
        $_.IdentityReference -eq $currentuser `
        -and $_.IsInherited -eq $False `
        -and $_.RegistryRights -eq "SetValue" `
        -and $_.AccessControlType -eq "Deny"
    }
    if ($rule) {
        $acl.RemoveAccessRuleSpecific($rule)
        $key.SetAccessControl($acl)
        Write-Debug 'Rule removed'
    } else {
        Write-Debug 'No matching rule found'
    }
$key.Close()
  • Related