Reputation: 1146
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?
Upvotes: 4
Views: 2727
Reputation: 4382
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 characterUpvotes: 2
Reputation: 6860
You can use Get-ChildItem -Directory -Recurse
,
This will do exactly what you are asking for. Pipe it from the array to a Remove-Item
@("C:\Windows\Temp\*", "C:\Documents and Settings\*\Local Settings\temp\*", "C:\Users\*\Appdata\Local\Temp\*") |
Get-ChildItem -Directory -Recurse -Force -ErrorAction SilentlyContinue |
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
Just for a heads up in Powershell Piping |
is key. PowerShell we love to chain commands.
Upvotes: 0