PowerShell - How can I use regex in the middle of registry file path to perform remove-item operation?

112 Views Asked by At

I've looked at many similar questions and tried lots of things, but I can't make it work.

$Regex = 'RegexPattern'
    
    
    Remove-Item -Path 'HKCU:System\somePath\' + $Regex + '\MorePath\*' -Recurse
    
    Remove-Item -Path "HKCU:System\somePath\$Regex\MorePath\*" -Recurse
    
    Remove-Item -Path "HKCU:System\somePath\$($Regex)\MorePath\*" -Recurse

    Remove-Item -Path "HKCU:System\somePath\'RegexPattern'\MorePath\*" -Recurse

    Remove-Item -Path 'HKCU:System\somePath\"RegexPattern"\MorePath\*' -Recurse

None of those work.

I have a regex, want to delete only children of a folder with remove-item but I don't know how to make it parse the regex instead of taking the pattern literally.

1

There are 1 best solutions below

1
On BEST ANSWER

The -Path parameter accepts wildcards, not regexes.

To apply regex matching, use Get-ChildItem, filter the results with Where-Object, which allows you to perform regex matching with the -match operator, and apply Remove-Item to the results; along the following lines:

Get-ChildItem -Path HKCU:\System\somePath\*\MorePath |
  Where-Object Name -match $RegexPattern | 
  Remove-Item -Recurse -WhatIf 

Note: The -WhatIf common parameter in the command above previews the operation. Remove -WhatIf and re-execute once you're sure the operation will do what you want.

Note:

  • The above uses wildcard * to match the keys of potential interest, to be filtered via the regex later; adjust as needed.

  • Since you're processing registry keys, .Name refers to the full, registry-native key path, such as HKEY_CURRENT_USER\System\..., given that the registry keys output by Get-ChildItem are represented as [Microsoft.Win32.RegistryKey] instances.

  • The Where-Object call uses simplified syntax, which in simple cases such as this enables a more concise syntax; it is the equivalent of the following:
    Where-Object { $_.Name -match $RegexPattern }