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?