Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading