I'm trying to figure out how delete the files in multiple filtered folders from the Get-Childitem cmdlet.
What i want is find all folders with the name "Cache" in a specific path (Get-Childitem). Then remove the files inside that Cache folder.
Powershell version: 5.1
The code below is not working probably, maybe bad wildcard choice etc.?
Get-ChildItem "$env:LOCALAPPDATA\" -recurse -Filter "Cache\*" | foreach ($_) {remove-item $_.fullname -WhatIf -recurse}
Hopefully someone can help me out, I'm kind of noob in this area:)
Thanks!
Since you are using the -Recurse
flag, you dont need to use \
in your filter. Following filter will give you all items (including files and directories) that has the word cache in it (like bla cache bla)
Get-ChildItem $env:LOCALAPPDATA -recurse -Filter "*Cache*"
Or you can use -ErrorAction
switch to silently continue when there is a failure to find all folders and files that has the name "cache".
Get-ChildItem $env:LOCALAPPDATA -recurse -Filter "Cache" -ErrorAction SilentlyContinue
Thank you for the explanation.
Using -Filter "*Cache*"
is not what i need. I want exact the folders with the name Cache.
If I'm using Get-ChildItem $env:LOCALAPPDATA -recurse -Filter "Cache" -ErrorAction SilentlyContinue | % { $_.FullName }
Get-ChildItem $env:LOCALAPPDATA -recurse -Filter "Cache" -ErrorAction SilentlyContinue | % { $_.FullName }
The output is for example:
C:\Users\xxx\xxxxx\Cache
C:\Users\x\xxxxx\Cache
C:\Users\xx\xxx\Cache
C:\Users\x\xxx\Acrobat\Cache
From there I want to remove the files and folders inside all folders with that name Cache, I just filtered from the Get-ChildItem
Example inside: C:\Users\x\xxx\Acrobat\Cache has files and folders like data_0, data_1, data_2, GPUCache(folder) etc. That I want to remove, but with every found cache folder ( foreach
)
Hopefully you understand my idea.
Thank you!
After some digging i found my solution.
Following code is working for me:
$base_dir = "$env:LOCALAPPDATA"
$name = 'Cache'
Get-ChildItem $base_dir -Recurse -Force | Where-Object {
$_.PSIsContainer -and
$_.Name -eq $name
} | Select-Object -Expand FullName | ForEach-Object {
Remove-Item "$_\*" -Recurse -whatif
}
(Remove -whatif, to remove the files)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.