Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive Wildcards in PowerShell

I'm trying to delete files in a specific set of folders with PowerShell. My code currently looks like this:

$tempfolders = @(
    "C:\Windows\Temp\*"
    "C:\Documents and Settings\*\Local Settings\temp\*"
    "C:\Users\*\Appdata\Local\Temp\*"
    )

Remove-Item $tempfolders -Recurse -Force -ErrorAction SilentlyContinue

I want to add a new folder to that list, with the following formula:

"C:\users\*\AppData\Local\Program\**\Subfolder"

where ** could be multiple subfolders of unknown length. For example, it could be settings\subsettings or it could be folder\settings\subsettings. Is there a way to do this?

like image 421
Randy Avatar asked Aug 30 '25 18:08

Randy


1 Answers

You can feed the full path of each file to a regex; this will return only the files that match your format, which you can then pipe to Remove-Item:

ls "C:\Users" -Recurse -Hidden | Where-Object { $_.FullName -imatch '^C:\\users\\([^\\]+)\\AppData\\Local\\Program\\(.*)\\Subfolder' }

Because regexes are considered write-only, a bit of explanation:

  • backslashes count as escape characters inside a regex and need to be doubled.
  • ([^\\]+) means one or more of any character except a backslash
  • .* means zero or more of any character
like image 168
Leon Bouquiet Avatar answered Sep 02 '25 22:09

Leon Bouquiet