Continuum Concepts

Recursively delete all bin and obj directories in PowerShell

The Issue

Sometimes I want to recursively delete all bin and obj folders in a solution. For example when tinkering with an asp.net project, changing packages/frameworks or otherwise editing the .csproj can cause builds to break. Even dotnet clean doesn't clean things up. That's when I use the PowerShell command explained below.

The Solution

Warning: If you use NPM and/or have a node_modules directory, you probably do NOT want to delete bin and obj folders under there. See the bottom of this article for how to handle it!

To DELETE all bin and obj folders in or below the current working directory, along with their contents:

Get-ChildItem -Include bin,obj -Recurse | ForEach-Object { $_ | Remove-Item -Recurse -Force -Verbose }

To LIST all bin and obj folders in or below the current working directory:

Get-ChildItem -Include bin,obj -Recurse | ForEach-Object { Write-Output $_.FullName }

How it Works

First, Get-ChildItem is called with the -Include bin,obj parameters, which says to only return directories named bin or obj. The -Recurse parameter is used to search within all subdirectories of the current path. This cmdlet is a bit like dir or ls, but can read from additional places (such as the registry).

The output of Get-ChildItem (i.e., all bin and obj directories) is then piped into ForEach-Object. This cmdlet executes a block of script (the code in braces) on each item in the input.

In this script block, $_ represents the current item being processed. This item is piped into Remove-Item, which deletes it. The -Recurse parameter tells Remove-Item to delete the item and all of its subitems. The -Force parameter suppresses prompts to confirm the deletion of read-only items. Finally, the -Verbose parameter outputs details of each operation (deletion).

Dealing with node_modules

If you're using node and have a node_modules folder, it may very well have bin and obj folders that you do not want to disturb.

To DELETE all bin and obj folders in or below the current working directory, along with their contents (excluding folders that have "node_modules" in the path):

Get-ChildItem -Recurse -Force | Where-Object {
    $_.PSIsContainer -and 
    ($_.FullName -notmatch 'node_modules') -and 
    ($_.Name -eq 'bin' -or $_.Name -eq 'obj')
} | ForEach-Object {
    Remove-Item -Path $_.FullName -Recurse -Force -Verbose
}

To LIST all bin and obj folders in or below the current working directory (excluding folders that have "node_modules" in the path):

Get-ChildItem -Recurse -Force | Where-Object {
    $_.PSIsContainer -and 
    ($_.FullName -notmatch 'node_modules') -and 
    ($_.Name -eq 'bin' -or $_.Name -eq 'obj')
} | ForEach-Object {
    Write-Output $_.FullName
}