1

I am deploying an update via WSUS to remove broken registry keys from Windows 10 systems running 1703 and 1709. The PowerShell code needs to open two registry keys, take ownership, set ownership to users, then delete them. The code below works when run from machines directly:

#Set our root registry key and new owner (Users)
$rootKey = "LocalMachine"
[System.Security.Principal.SecurityIdentifier]$sid = 'S-1-5-32-545'

#First key
$key = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileNotification\TDL"

#Take ownership and delete if it exists
if (Test-Path "HKLM:\$key") {
    $regKey = [Microsoft.Win32.Registry]::$rootKey.OpenSubKey($key, 'ReadWriteSubTree', 'TakeOwnership')
    $acl = New-Object System.Security.AccessControl.RegistrySecurity
    $acl.SetOwner($sid)
    $regKey.SetAccessControl($acl)
    $acl.SetAccessRuleProtection($false, $false)
    $regKey.SetAccessControl($acl)

    Remove-Item -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileNotification\TDL" -Force -Recurse
} else{
    Add-content $txtLogLocation "Key 1 does not exist."
}

However, I receive the following error when this code is run as the SYSTEM user (I deploy it via Windows Update, which runs this as SYSTEM):

Exception calling "OpenSubKey" with "3" argument(s): "Requested registry
access is not allowed."
At C:\Windows\TEMP\7zSAA99.tmp\1809ReadinessScript.ps1:224 char:2
+     $regKey = [Microsoft.Win32.Registry]::$rootKey.OpenSubKey($key, ' ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SecurityException

Exception calling "OpenSubKey" with "3" argument(s): "Requested registry
access is not allowed."
At C:\Windows\TEMP\7zSAA99.tmp\1809ReadinessScript.ps1:224 char:2
+     $regKey = [Microsoft.Win32.Registry]::$rootKey.OpenSubKey($key, ' ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SecurityException

Any thoughts on why this might be happening? Is it due to the SYSTEM user running it, or is it some odd PowerShell issue that requires a different method to handle opening registry keys?

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Tim P.
  • 11
  • 1
  • 4

1 Answers1

0

I was able to work around this issue by using PowerShell to create a scheduled task that then runs the script that is downloaded locally to the machine. The task runs as the local user, which has the ability to open the subkey and thus change the permissions. SYSTEM for whatever reason did not have read access to this particular key.

Tim P.
  • 11
  • 1
  • 4