Setting audit permission on the registry

I’m writing something that will go through permissions and remove permissions that are too high and replace them with ‘readkey’ permission…but I’m getting the below error using my code:

$path = "hklm:\software\whatever"
$user = "builtin\users"

foreach($acl in (get-acl $path).access | ?{$_.identityreference -eq $user} | ? {$_.accesscontroltype -eq "Allow"})
{

if($acl.registryrights -notmatch $permissions)
{

$x = (get-item -force $path).GetAccessControl('Access')
													
$rule = new-object system.security.accesscontrol.registryaccessrule($user, "readkey", "None", "none", "Allow")
											$x.RemoveAccessRuleSpecific($acl)
													$x.setaccessrule($rule)
													
#sets the ACL
(get-item $path).SetAccessControl($x)
Exception calling "SetAccessControl" with "1" argument(s): "Cannot write to the registry key."
At line:1 char:34
+ (get-item $path).setaccesscontrol <<<< ($x)
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

I am a system admin on this PC.

Hey ertuu85,

Still looking through your code, but first things that stand out are that you don’t seem to have defined/pasted a value for $permissions, and closed braces in the script?

Is this the entire script?

$permissions = "readkey|ReadPermissions"

The above checks for read/read permissions for registry values

Should be noted, when I do this one files/folders I get no errors…just on registry entries.