湖边的白杨树

探索是一种乐趣

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Task: 删除HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USB\VID_0XXX&PID_0XXX Key Tree

首先第一想到的使用PS Script来删除: 

Remove-Item -Path 'Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USB\VID_045E&PID_07DC'

 但是发现如果想删除USB Enum的话需要很高的权限,即使使用Admin权限,也遭到拒绝。

Remove-Item : Requested registry access is not allowed.
At D:\Debug_Local\RemoveRegistry.ps1:2 char:1
+ Remove-Item -Path 'Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\US ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (HKEY_LOCAL_MACH...rolSet\Enum\USB:String) [Remove-Item], SecurityException
    + FullyQualifiedErrorId : System.Security.SecurityException,Microsoft.PowerShell.Commands.RemoveItemCommand

随后开始考虑用C#程序来删除。同时安装为Windows Service来获取System权限,来删除之。

foreach (var registryKey in usbRegistryList)
            {
                string keyPath = string.Format(@"SYSTEM\CurrentControlSet\Enum\USB\{0}", registryKey);
                using (RegistryKey key = Registry.LocalMachine.OpenSubKey(keyPath, true))
                {
                    if (key == null)
                    {
                        this.log.Append(this.GetCurrentDateTime()).Append(string.Format("The key {0} does not exist!", key)).Append(Environment.NewLine);  
                    }
                    else
                    {
                        try
                        {
                            foreach (var subKey in key.GetSubKeyNames())
                            {
                                key.DeleteSubKeyTree(subKey);
                                this.log.Append(this.GetCurrentDateTime()).AppendFormat("The sub key {0} is removed sucessfully!", subKey).Append(Environment.NewLine); 
                            }
                        }
                        catch (Exception ex)
                        {
                            this.log.AppendFormat("Error is found during removing key {0}. Details:{1}", key, ex.Message).Append(Environment.NewLine); 
                        }
                    }
                }
            }

 

posted on 2014-04-25 13:50  fdyang  阅读(2669)  评论(0编辑  收藏  举报