Powershell: delete all the registry keys containing a string

12,850

Try the following script:

$RE = 'Python35'
$Key = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-2\Components'
Get-ChildItem $Key -Rec -EA SilentlyContinue | ForEach-Object {
   $CurrentKey = (Get-ItemProperty -Path $_.PsPath)
   If ($CurrentKey -match $RE){
     $CurrentKey|Remove-Item -Force -Whatif
   }
}

If the output looks OK remove the -WhatIf paramter from Remove-Item

Share:
12,850
MagTun
Author by

MagTun

Updated on June 16, 2022

Comments

  • MagTun
    MagTun almost 2 years

    I would like to delete all the keys (1000+) containing Python35 from :HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-2\Components

    For instance I would like to delete all the keys similar to that one:

    • Keyname: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-2\Components\0027CAECCC428F356B8D845FF8331246

    • Name: 0F617A7B1C879BC47865E0155CDD6722

    • Data: C:\Users\Me\AppData\Local\Programs\Python\Python35\Lib\venv\__init__.py

    I tried this.

    Get-ChildItem -path HKLM:SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-2\Components\ -Recurse | where { $_.Name -match 'Python35'} | Remove-Item -Force
    

    Powershell runs without error,but when I check it in the registry, the keys are still there.

    Powershell is run as admin and Admin has the ownership of the key HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-2\Components and also full control on that key and its subkeys.

    • Admin
      Admin almost 7 years
      What output do you get if you omit the Remove-Item, is there any? Check the properties of Get-ChildItem HKLM:key |Get-Member
    • MagTun
      MagTun almost 7 years
      No output if I omit the | Remove-Item -Force part. I didn't find a Get-ChildItem in the list cf paste.ubuntu.com/24664764
    • restless1987
      restless1987 almost 7 years
      Your example key does say Python36 and not Python35. This will not match.
    • MagTun
      MagTun almost 7 years
      Sorry, I took the wrong key, there are keys containing Python35
  • MagTun
    MagTun almost 7 years
    It's working but I wonder why the code my question doesn't work.
  • Admin
    Admin almost 7 years
    I think the Get-ChildItem output from the registry provider isn't directly parseable