尝试搜索和删除注册SubKeyTree时出错

时间:2016-05-05 18:11:38

标签: powershell

我正在尝试根据路径数组从寄存器中删除一些键,我会搜索几个关键字并想要删除找到该子项的“树”。

但是在尝试弄清楚之后,下面的脚本总是会返回此错误:

It's not possible to call a method in an expression witha null value.
At line:17 character:1
+ $SubKeys=$RegisterKey.GetSubKeyNames()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull
Begin
{
     $computername = $env:computername
     "Script Started $(Get-Date)"
     [array]$KeysToRemove="HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall","HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\Installer\\Products","HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\OnlineManagement","HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Installer\\UserData\\S-1-5-18\\Products","HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Installer\\UserData\\S-1-5-18\\Components","HKEY_CLASSES_ROOT\\Installer\\Products"
}
Process
{
     foreach($keys in $KeysToRemove)
     {
          if($KeysToRemove -eq "HKEY_CLASSES_ROOT\\Installer\\Products")
          {$Register = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('ClassesRoot', $computername)}
          else {$Register = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $computername)}

          $RegisterKey = $Register.OpenSubKey($keys)

          $SubKeys=$RegisterKey.GetSubKeyNames()

          foreach($key in $SubKeys){
               if($key.Contains('Microsoft\.Intune'))
               {
                    "Key found: $key"
                    "Deleting it from register."
                    $Register.DeleteSubKeyTree($key)
               }
               else {"No key was found."}
          }

     }
"Script Ended $(Get-Date)"
}

1 个答案:

答案 0 :(得分:1)

需要注意的几件事情:

\\

在PowerShell中,字符串转义字符是反引号`,而不是反斜杠\。不要尝试在注册表项字符串中转义\,这完全没必要。

HKEY_LOCAL_MACHINE

由于您已经打开了基本密钥(HKLMHKCR),因此您只需指定密钥的 relative 路径 - 这是最有可能失败的原因:

$HKLMRegistry = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $computername)
$UninstallKey = $HKLMRegistry.OpenSubkey("SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall")

# Now you can call GetSubKeyNames()
$SubKeyNames = $UninstallKey.GetSubKeyNames()

如果要迭代给定键上的所有值,请使用GetValueNames()GetValue()方法:

$UninstallKey.GetValueNames() |ForEach-Object {
    $Value = $UninstallKey.GetValue($_)
    Write-Host 'Value name: {0} had data: {1}' -f $_,$Value
}