Search code examples
powershellfilecachingfilterget-childitem

Powershell - Remove files inside the filtered folder


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!


Solution

  • 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)