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?
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:
([^\\]+)
means one or more of any character except a backslash.*
means zero or more of any characterIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With