Avoid recursively fetching specific folders in PowerShell

I have a Visual Studio solution with multiple projects. I am cleaning the bin and obj folders as part of the cleaning using the following script.

Get-ChildItem -path source -filter obj -recurse | Remove-Item -recurse
Get-ChildItem -path source -filter bin -recurse | Remove-Item -recurse

      

This works great. However, I have a file data folder that contains about 600,000 subfolders and it is in a folder named FILE_DATA.

The above script takes a long time because it goes through all those 600,000 folders.

I need to avoid the FILE_DATA folder when I recursively navigate and delete the bin and obj folders.

+3


source to share


2 answers


If the FILE_DATA folder is a subfolder of the source $ (no deeper) try:



$source = "C:\Users\Frode\Desktop\test"
Get-Item -Path $source\* -Exclude "FILE_DATA" | ? {$_.PSIsContainer} | % {
    Get-ChildItem -Path $_.FullName -Filter "obj" -Recurse | Remove-Item -Recurse
    Get-ChildItem -Path $_.FullName -Filter "bin" -Recurse | Remove-Item -Recurse
}

      

+2


source


Here's a more efficient approach that does what you want - skip the subtrees you want to exclude:

function GetFiles($path = $pwd, [string[]]$exclude)
{
    foreach ($item in Get-ChildItem $path)
    {
        if ($exclude | Where {$item -like $_}) { continue }

        $item
        if (Test-Path $item.FullName -PathType Container)
        {
            GetFiles $item.FullName $exclude
        }
    }
} 

      

This code is adapted from Keith Hill's answer to this post ; my contribution is bug fixes and minor refactorings; you will find a full explanation in my answer to the same SO question.



This call should do what you want:

GetFiles -path source -exclude FILE_DATA

      

For an even more leisurely read, check out my article on Simple-Talk.com that discusses this and more: Practical PowerShell: Pruning Tree Files and Extending Cmdlets .

+2


source







All Articles