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.
The
-Path
parameter accepts wildcards, not regexes.To apply regex matching, use
Get-ChildItem
, filter the results withWhere-Object
, which allows you to perform regex matching with the-match
operator, and applyRemove-Item
to the results; along the following lines: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 asHKEY_CURRENT_USER\System\...
, given that the registry keys output byGet-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 }