求助:如何通过脚本修改System拥有的注册表项所有权并批量删除该注册表项
求助:如何通过脚本修改System拥有的注册表项所有权并批量删除该注册表项
我现在遇到个棘手的问题:想通过脚本批量修改并删除由System账户拥有的注册表项,但试了CMD和PowerShell的好几种方法都失败了,手动操作明明是可行的,想问问大家有没有可行的方案?
先说说手动操作的成功步骤:
- 打开注册表项的权限设置 → 高级选项
- 将所有者改为我自己的账户
- 添加权限条目给我自己,设置为完全控制
- 勾选「替换子容器和对象的所有者」以及「替换所有子对象权限条目为该对象的可继承权限条目」
- 最后删除该注册表项
但换成脚本执行就各种报错,下面是我试过的方法和对应的错误:
试过的CMD方法
方法1
reg add "HKEY_LOCAL_MACHINE\Path_To_Key\Key_Name" /f /t REG_SZ /d username /reg:64
错误提示:ERROR: Access is denied.
方法2
takeown /f "HKEY_LOCAL_MACHINE\Path_To_Key\Key_Name"
错误提示:ERROR: The system cannot find the path specified.
试过的PowerShell方法
方法1
$keyPath = "HKEY_LOCAL_MACHINE\SYSTEM\Path_To_Key\Key_Name" $username = "username" $key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($keyPath, [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree, [System.Security.AccessControl.RegistryRights]::TakeOwnership) $acl = $key.GetAccessControl() $acl.SetOwner([System.Security.Principal.NTAccount] $username) $key.SetAccessControl($acl) $key.Close()
错误提示:
You cannot call a method on a null-valued expression. At line:1 char:1 + $acl = $key.GetAccessControl() + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull
方法2
$keyPath = "HKLM:\SYSTEM\Path_To_Key\Key_Name" $owner = "YOUR_USERNAME" # Take ownership $key = [Microsoft.Win32.Registry]::OpenBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, [Microsoft.Win32.RegistryView]::Registry64).OpenSubKey($keyPath, [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree, [System.Security.AccessControl.RegistryRights]::TakeOwnership) $acl = $key.GetAccessControl() $acl.SetOwner([System.Security.Principal.NTAccount] $owner) [Microsoft.Win32.Registry]::SetAccessControl($keyPath, $acl)
错误提示:
Method invocation failed because [Microsoft.Win32.Registry] does not contain a method named 'OpenBaseKey'. At line:5 char:1 + $regKey = [Microsoft.Win32.Registry]::OpenBaseKey([Microsoft.Win32.Re ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : MethodNotFound
另外我还试过其他一些方案,包括看到的一些建议,但也都报了「You cannot call a method on a null-valued expression」的错误。
更奇怪的是,我用桌面管理工具以nt authority\system身份启动CMD去删除这个注册表项,居然也报ERROR: Access is denied.。
既然手动用管理员账户能搞定,那肯定有脚本实现的办法吧?有没有大佬能指点下思路?非常感谢!
备注:内容来源于stack exchange,提问作者Patrick Keane
相关产品推荐
相关产品推荐

