Here's a well-documented PowerShell script that recursively deletes all bin and obj folders from a specified root directory and its subdirectories. It first collects the folder paths, outputs them, and then deletes them, ensuring you can review what will be removed before proceeding.
✅ Features:
- Collects all
bin and obj folders recursively.
- Outputs the list of folders before deletion.
- Deletes the folders with
-Force to handle read-only files.
- Optional confirmation step (commented out by default).
- Allows specifying a custom root directory via a parameter.
📝 Script: Clean-BinObjFolders.ps1
<#
.SYNOPSIS
Removes all "bin" and "obj" folders recursively from the specified directory.
.DESCRIPTION
This script searches for and deletes all directories named "bin" or "obj"
within the specified root path and its subdirectories.
.PARAMETER StartPath
The root directory to start searching from. Defaults to the current directory.
.EXAMPLE
.\Clean-BinObjFolders.ps1
.\Clean-BinObjFolders.ps1 -StartPath "C:\MySolution"
#>
[CmdletBinding()]
param (
[string]$StartPath = "."
)
# Normalize the path
$StartPath = Resolve-Path -Path $StartPath
# Find all bin and obj folders recursively
Write-Verbose "Searching for 'bin' and 'obj' folders in '$StartPath' and subdirectories..."
$folders = Get-ChildItem -Path $StartPath -Recurse -Directory |
Where-Object { $_.Name -in @("bin", "obj") } |
Select-Object -ExpandProperty FullName
if ($folders) {
Write-Host "Found the following folders to delete:" -ForegroundColor Yellow
$folders | ForEach-Object { Write-Host $_ }
# 🔒 Uncomment the following lines to confirm before deletion
# $confirm = Read-Host "Proceed with deletion? (Y/N)"
# if ($confirm -ne 'Y') {
# Write-Host "Operation cancelled." -ForegroundColor Red
# return
# }
# Delete the folders
Write-Host "Deleting folders..." -ForegroundColor Green
$folders | ForEach-Object {
Remove-Item -Path $_ -Force -Recurse
Write-Host "Deleted: $_"
}
Write-Host "✅ All bin and obj folders have been deleted successfully." -ForegroundColor Green
} else {
Write-Host "No 'bin' or 'obj' folders found in '$StartPath' or its subdirectories." -ForegroundColor Green
}
🧪 How to Use:
- Save the script as
Clean-BinObjFolders.ps1.
- Open PowerShell in the folder where the script is saved.
- Run it with:
.\Clean-BinObjFolders.ps1
- To specify a different root folder:
.\Clean-BinObjFolders.ps1 -StartPath "C:\Your\Project\Root"
- For testing, add
-WhatIf to the Remove-Item line to simulate deletion:
Remove-Item -Path $_ -Force -Recurse -WhatIf
⚠️ Safety Note:
This script deletes files permanently. Always test with -WhatIf before running it in a production environment.
This script is ideal for cleaning up Visual Studio solution directories or other environments where bin and obj folders are common.