Use PowerShell to Clean your Visual Studio solution

There are lots of times when I want to do a "Clean" of my VS.NET solution.  Obviously, the most common way to do this is to right-click your solution in the solution explorer and select "Clean Solution".  However, there are 2 drawbacks of this.  One is that if you have files sitting in your bin or obj directories that are not in some way linked to your solution, they won't be removed.  Additionally, sometimes you just want to do a quick clean of a directory structure without having to fire up VS.NET.

You could use MSBuild to do this to avoid having to fire up VS.NET by doing a command like this:

**MSBuild MyApp.sln /t:Clean**

However, that still leaves you with the problem of leaving the orphaned files. 

I often just want to completely delete the bin and obj directories.  This might be because I want to ensure I'm truly starting fresh.  Or it may be because of have a little sample solution that I just want to throw into a ZIP file to upload or send to someone.  In that case, I want the bin and obj directories to not even exist.

I've found the easiest way to do this is to just use a little PowerShell function.  The function is called "cleanBin" and you simply pass a single command line argument which is the location of your solution root. It can be invoked by simply using this command:

**PS C:scripts> cleanBin C:tempSomeSolution**

It will recursively look at every folder under your solution root and remove and bin or obj directories.  The complete function definition is as follows:

 function cleanBin {
     param ([string]$path)
     write-host "Cleaning bin from: $path"
     get-childitem $path -include bin -recurse | remove-item
     write-host "Cleaning obj from: $path"
     get-childitem $path -include obj -recurse | remove-item

For re-usable functions like this, the easiest way to ensure that they are always globally accessible to you is to put them in your PowerShell profile file.  This file gets automatically run any time you start PowerShell.  You should have a folder inside your "My Documents" called "WindowsPowerShell".  Simply put a text file in that folder called "Microsoft.PowerShell_profile.ps1" and paste the above function in there.

Technorati Tags: PowerShell