314

I work with multiple projects, and I want to recursively delete all folders with the name 'bin' or 'obj' that way I am sure that all projects will rebuild everything (sometimes it's the only way to force Visual Studio to forget all about previous builds).

Is there a quick way to accomplish this (with a .bat file for example) without having to write a .NET program?

Lauren Van Sloun
  • 1,070
  • 5
  • 17
  • 20
MichaelD
  • 6,739
  • 9
  • 37
  • 45

26 Answers26

496

This depends on the shell you prefer to use.

If you are using the cmd shell on Windows then the following should work:

FOR /F "tokens=*" %%G IN ('DIR /B /AD /S bin') DO RMDIR /S /Q "%%G"
FOR /F "tokens=*" %%G IN ('DIR /B /AD /S obj') DO RMDIR /S /Q "%%G"

If you are using a bash or zsh type shell (such as git bash or babun on Windows or most Linux / OS X shells) then this is a much nicer, more succinct way to do what you want:

find . -iname "bin" | xargs rm -rf
find . -iname "obj" | xargs rm -rf

and this can be reduced to one line with an OR:

find . -iname "bin" -o -iname "obj" | xargs rm -rf

Note that if your directories of filenames contain spaces or quotes, find will send those entries as-is, which xargs may split into multiple entries. If your shell supports them, -print0 and -0 will work around this short-coming, so the above examples become:

find . -iname "bin" -print0 | xargs -0 rm -rf
find . -iname "obj" -print0 | xargs -0 rm -rf

and:

find . -iname "bin" -o -iname "obj" -print0 | xargs -0 rm -rf

If you are using Powershell then you can use this:

Get-ChildItem .\ -include bin,obj -Recurse | foreach ($_) { remove-item $_.fullname -Force -Recurse }

as seen in Robert H's answer below - just make sure you give him credit for the powershell answer rather than me if you choose to up-vote anything :)

It would of course be wise to run whatever command you choose somewhere safe first to test it!

Brondahl
  • 5,168
  • 1
  • 25
  • 45
Steve Willcock
  • 23,749
  • 4
  • 41
  • 39
  • 6
    thx for your answer. I get an error: %%G was unexpected at this time. – MichaelD Apr 16 '09 at 12:32
  • Hmm that's odd - it works fine on my machine (vista 64bit business) - I'll try it on an xp machine too. – Steve Willcock Apr 16 '09 at 12:53
  • allright i got it to work. one strange issue is that when there is a bin folder in the root he doesn't delete anything. but that doesn't matter – MichaelD Apr 16 '09 at 13:24
  • have you got any idea how i let the script search in a folder other than it's running from? – MichaelD Apr 16 '09 at 14:18
  • got it, by doing: r: FOR /F "tokens=*" %%G IN ('DIR /B /AD /S obj') DO RMDIR /S /Q "%%G" FOR /F "tokens=*" %%G IN ('DIR /B /AD /S bin') DO RMDIR /S /Q "%%G" Pause – MichaelD Apr 16 '09 at 14:25
  • Note that iterating over `dir` output in this way can lead to unexpected failures with Unicode file or directory names and the console being set to Raster fonts. Characters that won't fit into the OEM codepage will be converted to their nearest equivalent or `?`. The most likely result is that whatever you're doing with the output it just cannot find the files. Note that this doesn't happen if you use `for` to iterate. – Joey May 12 '11 at 09:57
  • 55
    "%%G was unexpected at this time" - this happens when you run it from the command line instead from inside a batch file. Use single '%'s in this case. – Designpattern Jan 11 '12 at 09:05
  • 4
    +1 Would you mind to explain the code for me? Please. – fiberOptics Feb 06 '14 at 03:54
  • 2
    @SteveWillcock It's better than clean. Clean won't remove dlls that are not referenced in the project anymore (leftovers). – Piotr Szmyd Nov 20 '14 at 14:50
  • Doesn't work in Windows 8. The powershell script below works. – cbp Dec 11 '14 at 00:17
  • We can use 'name' instead of 'iname' if you want to do the search case-sensitive. find . -name "bin" | xargs rm -rf – Ramaraj T Jun 27 '18 at 09:41
  • Make sure you don't have any programs open that have locked the files. Otherwise you might get strange access denied errors. – Jim Aho Dec 04 '18 at 10:59
  • 1
    I would suggest excluding node_modules if you have it. A lot of packages have their own bin folder (like Gulp) and it can cause things to break if you delete them. You'll likely have to run `npm install` to repopulate the bin folder. – JED Apr 15 '20 at 19:11
  • I had the some need as JED, I excluded the node_modules with this command. `Get-ChildItem -Recurse -include bin,obj | Where-Object {$_.FullName -notMatch "node_modules"}` After this you can pipe into the foreach as mentioned in the answer. – JabberwockyDecompiler Jul 24 '20 at 15:26
  • I don't recommend those commands. I've tried it and it messed up my entire repository. Looks like it entered inside the .git folders and messed everything up –  Nov 26 '20 at 20:30
315

I found this thread and got bingo. A little more searching turned up this power shell script:

Get-ChildItem .\ -include bin,obj -Recurse | ForEach-Object ($_) { Remove-Item $_.FullName -Force -Recurse }

I thought I'd share, considering that I did not find the answer when I was looking here.

Morse
  • 5,778
  • 5
  • 31
  • 55
Robert H.
  • 4,244
  • 1
  • 20
  • 24
  • @Nigel, Isn't this solution extremely un-performant? Why not write a custom C script that can run at 10x the speed? – Pacerier Jan 03 '15 at 01:24
  • 43
    You don't need the foreach - you should just be able to pipe gci straight into remove-item (i.e., `gci -include bin,obj -recurse | remove-item -force -recurse`) – Chris J Mar 16 '15 at 11:54
  • 3
    I needed to also exclude folders from the searchpath, and I like the `-WhatIf` flag to test first, so I ended up with this: `$foldersToRemove='bin','obj';[string[]]$foldersToIgnore='ThirdParty';Get-ChildItem .\ -Include $foldersToRemove -Recurse|Where-Object{$_.FullName -inotmatch "\\$($foldersToIgnore -join '|')\\"}|Remove-Item -Force -Recurse -WhatIf` (a bit messy here as one line though :) ) – Johny Skovdal Apr 16 '18 at 08:32
  • @ChrisJ Consider adding a new answer with your solution. – granadaCoder May 19 '20 at 20:13
  • This doesn't work as expected, I get a lot of error messages like: `remove-item : Impossible de supprimer l'élément C:\Projects\...: Impossible de trouver une partie du chemin d'accès 'AccessibilityManagerCompat_AccessibilityStateChangeListenerImplementor.class'. + CategoryInfo : WriteError: (AccessibilityMa...plementor.class:FileInfo) [Remove-Item], DirectoryNotFoundException + FullyQualifiedErrorId : RemoveFileSystemItemIOError,Microsoft.PowerShell.Commands.RemoveItemCommand` – Gold.strike Jan 21 '21 at 08:30
74

This worked for me:

for /d /r . %%d in (bin,obj) do @if exist "%%d" rd /s/q "%%d"

Based on this answer on superuser.com

Community
  • 1
  • 1
Daniel Rehner
  • 1,611
  • 12
  • 8
33

I use to always add a new target on my solutions for achieving this.

<Target Name="clean_folders">
  <RemoveDir Directories=".\ProjectName\bin" />
  <RemoveDir Directories=".\ProjectName\obj" />
  <RemoveDir Directories="$(ProjectVarName)\bin" />
  <RemoveDir Directories="$(ProjectVarName)\obj" />
</Target>

And you can call it from command line

msbuild /t:clean_folders

This can be your batch file.

msbuild /t:clean_folders
PAUSE
Dan Atkinson
  • 10,801
  • 12
  • 78
  • 106
Jhonny D. Cano -Leftware-
  • 16,647
  • 12
  • 77
  • 100
  • This does not work for a sln file since you cannot call custom targets on them or do you know a workaround for this – Piotr Owsiak Nov 03 '10 at 12:44
  • 3
    @PiotrOwsiak yes, you need to create file "before.MySlnFileName.sln.targets" in the same directory where you have your .sln and put there your target definitions – Endrju Oct 06 '14 at 10:28
  • 2
    you can add AfterTargets="Clean" as an attribute to the Target, it will be automatically called after the Clean which is invoked directly or indirectly when doing a rebuild – Newtopian Nov 24 '15 at 16:07
29

I wrote a powershell script to do it.

The advantage is that it prints out a summary of deleted folders, and ignored ones if you specified any subfolder hierarchy to be ignored.

Output example

doblak
  • 2,766
  • 1
  • 23
  • 21
  • 1
    +1 very nice! Just found out that we can actually debug and see the variables like a full-fetch debugger in Window Power Shell! – wiz_lee Apr 24 '15 at 08:17
  • I like this solution. I don't have to mess with Visual Studio and I can run this when I want. Very nice! – Halcyon Aug 07 '15 at 18:54
  • Suits my needs perfectly, but I'm not sure why this couldn't be a gist rather than a full-blown repo. :-) – Dan Atkinson Dec 29 '16 at 00:03
  • Nice work! I would omit all directories scanning because when you have thousands of subdirectories, this could be quite slow. Too high price just for statistics :-). Also I would add `$_ -notmatch 'node_modules'` condition to `$FoldersToRemove` variable definition – Tomino May 24 '17 at 08:04
16

Nothing worked for me. I needed to delete all files in bin and obj folders for debug and release. My solution:

1.Right click project, unload, right click again edit, go to bottom

2.Insert

<Target Name="DeleteBinObjFolders" BeforeTargets="Clean">
  <RemoveDir Directories="..\..\Publish" />
  <RemoveDir Directories=".\bin" />
  <RemoveDir Directories="$(BaseIntermediateOutputPath)" />
</Target>

3. Save, reload project, right click clean and presto.

Kdefthog
  • 161
  • 1
  • 4
12

NB: This is an old answer and may need a tweak for newer versions as of VS 2019 and some obj artifacts. Before using this approach, please make sure VS doesn't need anything in your target and output directory to build successfully.

Something like that should do it in a pretty elegant way, after clean target:

<Target Name="RemoveObjAndBin" AfterTargets="Clean">
    <RemoveDir Directories="$(BaseIntermediateOutputPath)" />
    <RemoveDir Directories="$(TargetDir)" />
</Target>
vezenkov
  • 3,289
  • 24
  • 27
  • In VS2019 i found out that this makes the IDE hang for quite some time and has issues with Rebuild and project.assets.json – Mattias Cibien Mar 12 '21 at 09:22
  • 1
    Thanks Mattias, I have added a warning. I guess it depends on the project type and maybe not a good idea to fully clean some of the projects. There should be a tweak for that. – vezenkov Mar 25 '21 at 21:43
7

To delete bin and obj before build add to project file:

<Target Name="BeforeBuild">
    <!-- Remove obj folder -->
    <RemoveDir Directories="$(BaseIntermediateOutputPath)" />
    <!-- Remove bin folder -->
    <RemoveDir Directories="$(BaseOutputPath)" />
</Target>

Here is article: How to remove bin and/or obj folder before the build or deploy

Shaman
  • 3,306
  • 2
  • 21
  • 18
  • 1
    You'll only want to do this on a rebuild, though. Unless you want _every_ build to be a rebuild! – Josh M. Oct 22 '15 at 10:55
6

Very similar to Steve's PowerShell scripts. I just added TestResults and packages to it as it is needed for most of the projects.

Get-ChildItem .\ -include bin,obj,packages,TestResults -Recurse | foreach ($_) { remove-item $_.fullname -Force -Recurse }
Aboo
  • 2,074
  • 1
  • 17
  • 20
5

A very quick and painless way is to use the rimraf npm utility, install it globally first:

> npm i rimraf -g

And then the command from your project root is quite simple (which can be saved to a script file):

projectRoot> rimraf **/bin **/obj

To optimize the desired effect you can leverage the project event targets (the one you could use is BeforeRebuild and make it run the previous command) which are specified in the docs: https://docs.microsoft.com/en-us/visualstudio/msbuild/how-to-extend-the-visual-studio-build-process?view=vs-2017

I like the rimraf utility as it is crossplat and really quick. But, you can also use the RemoveDir command in the .csproj if you decide to go with the target event option. The RemoveDir approach was well explained in another answer here by @Shaman: https://stackoverflow.com/a/22306653/1534753

Vedran Mandić
  • 582
  • 5
  • 14
3

Have a look at the CleanProject, it will delete bin folders, obj folders, TestResults folders and Resharper folders. The source code is also available.

habakuk
  • 2,416
  • 2
  • 27
  • 45
  • The project appears to have moved to here: https://code.msdn.microsoft.com/windowsdesktop/Clean-Cleans-Visual-Studio-a05bca4f – Johny Skovdal Apr 16 '18 at 08:24
3

from Using Windows PowerShell to remove obj, bin and ReSharper folders

very similar to Robert H answer with shorter syntax

  1. run powershell
  2. cd(change dir) to root of your project folder
  3. paste and run below script

    dir .\ -include bin,obj,resharper* -recurse | foreach($) { rd $_.fullname –Recurse –Force}

Community
  • 1
  • 1
Iman
  • 15,560
  • 6
  • 70
  • 83
3

Here is the answer I gave to a similar question, Simple, easy, works pretty good and does not require anything else than what you already have with Visual Studio.

As others have responded already Clean will remove all artifacts that are generated by the build. But it will leave behind everything else.

If you have some customizations in your MSBuild project this could spell trouble and leave behind stuff you would think it should have deleted.

You can circumvent this problem with a simple change to your .*proj by adding this somewhere near the end :

<Target Name="SpicNSpan"
        AfterTargets="Clean">
    <RemoveDir Directories="$(OUTDIR)"/>
</Target>

Which will remove everything in your bin folder of the current platform/configuration.

Community
  • 1
  • 1
Newtopian
  • 7,001
  • 4
  • 46
  • 70
3

This is my batch file that I use for deleting all BIN and OBJ folders recursively.

  1. Create an empty file and name it DeleteBinObjFolders.bat
  2. Copy-paste code the below code into the DeleteBinObjFolders.bat
  3. Move the DeleteBinObjFolders.bat file in the same folder with your solution (*.sln) file.
@echo off
@echo Deleting all BIN and OBJ folders...
for /d /r . %%d in (bin,obj) do @if exist "%%d" rd /s/q "%%d"
@echo BIN and OBJ folders successfully deleted :) Close the window.
pause > nul
Alper Ebicoglu
  • 6,488
  • 1
  • 34
  • 39
  • 1
    I just put this script on my desktop - but added the line `cd C:\Git\Workspace` after the first line... – James S Apr 14 '21 at 12:55
2

I use a slight modification of Robert H which skips errors and prints the delete files. I usally also clear the .vs, _resharper and package folders:

Get-ChildItem -include bin,obj,packages,'_ReSharper.Caches','.vs' -Force -Recurse | foreach ($_) { remove-item $_.fullname -Force -Recurse -ErrorAction SilentlyContinue -Verbose}

Also worth to note is the git command which clears all changes inclusive ignored files and directories:

git clean -dfx
tetralobita
  • 424
  • 5
  • 15
eugstman
  • 758
  • 1
  • 10
  • 17
2

Is 'clean' not good enough? Note that you can call msbuild with /t:clean from the command-line.

Brian
  • 113,581
  • 16
  • 227
  • 296
  • 7
    Indeed "clean" is not good enough. This is especially true when using MEF. "Clean Solution" does not get rid of references you've removed which can cause issues when dynamically loading a folder's DLLs. – Alex Apr 18 '12 at 12:33
  • 5
    A lot of "works on my machine" bugs are caused by old or unexpected stuff sitting around in the bin/obj folders that is not removed by doing a "clean". – Luke Apr 16 '14 at 18:17
1

http://vsclean.codeplex.com/

Command line tool that finds Visual Studio solutions and runs the Clean command on them. This lets you clean up the /bin/* directories of all those old projects you have lying around on your harddrive

Joel Martinez
  • 44,051
  • 25
  • 123
  • 182
1

On our build server, we explicitly delete the bin and obj directories, via nant scripts.

Each project build script is responsible for it's output/temp directories. Works nicely that way. So when we change a project and add a new one, we base the script off a working script, and you notice the delete stage and take care of it.

If you doing it on you logic development machine, I'd stick to clean via Visual Studio as others have mentioned.

Simeon Pilgrim
  • 9,300
  • 26
  • 32
  • sometimes i just have to be sure that all builds are completely new. I can't trust clean solution for doing that.deleting bin and obj has often proven more reliable – MichaelD Apr 16 '09 at 12:36
  • For us, only builds from the 'build machine' are tested, or used in production, so the developers don't have must be 'all clean' type issues, and the build server does that. Also means no one developer is needed to make a full build. – Simeon Pilgrim Apr 16 '09 at 20:45
  • 1
    What is the easiest way to do this with nant? I have A hierarchy of a couple dozen projects and I'd rather not misfire on a delete script. =) – mpontillo Oct 07 '10 at 22:25
  • We have many executables/dlls 'asset' built, so per asset we have a nant script that builds it. For each one there is a Delete section where we place a line for each debug/release bin/obj directory we want deleted. – Simeon Pilgrim Oct 10 '10 at 16:04
1

I actually hate obj files littering the source trees. I usually setup projects so that they output obj files outside source tree. For C# projects I usually use

 <IntermediateOutputPath>..\..\obj\$(AssemblyName)\$(Configuration)\</IntermediateOutputPath>

For C++ projects

 IntermediateDirectory="..\..\obj\$(ProjectName)\$(ConfigurationName)"
Juozas Kontvainis
  • 8,653
  • 6
  • 50
  • 65
1

You could actually take the PS suggestion a little further and create a vbs file in the project directory like this:

Option Explicit
Dim oShell, appCmd
Set oShell  = CreateObject("WScript.Shell")
appCmd      = "powershell -noexit Get-ChildItem .\ -include bin,obj -Recurse | foreach ($_) { remove-item $_.fullname -Force -Recurse -WhatIf }"
oShell.Run appCmd, 4, false

For safety, I have included -WhatIf parameter, so remove it if you are satisfied with the list on the first run.

KL XL
  • 11
  • 1
0

Considering the PS1 file is present in the currentFolder (the folder within which you need to delete bin and obj folders)

$currentPath = $MyInvocation.MyCommand.Path
$currentFolder = Split-Path $currentPath

Get-ChildItem $currentFolder -include bin,obj -Recurse | foreach ($_) { remove-item $_.fullname -Force -Recurse }
ShivanandSK
  • 629
  • 6
  • 13
0

For the solution in batch. I am using the following command:

FOR /D /R %%G in (obj,bin) DO @IF EXIST %%G IF %%~aG geq d RMDIR /S /Q "%%G"


The reason not using DIR /S /AD /B xxx
1. DIR /S /AD /B obj will return empty list (at least on my Windows10) enter image description here
2. DIR /S /AD /B *obj will contain the result which is not expected (tobj folder) enter image description here

xianyi
  • 31
  • 4
  • ```@IF EXIST %%G IF %%~aG geq d``` is used for checking path existing and the path is a folder not a file. – xianyi Jan 07 '19 at 06:10
0

This Works Fine For Me: start for /d /r . %%d in (bin,obj, ClientBin,Generated_Code) do @if exist "%%d" rd /s /q "%%d"

0

I use .bat file with this commad to do that.

for /f %%F in ('dir /b /ad /s ^| findstr /iles "Bin"') do RMDIR /s /q "%%F"
for /f %%F in ('dir /b /ad /s ^| findstr /iles "Obj"') do RMDIR /s /q "%%F"
Hacko
  • 1,391
  • 1
  • 14
  • 10
0

We have a large .SLN files with many project files. I started the policy of having a "ViewLocal" directory where all non-sourcecontrolled files are located. Inside that directory is an 'Inter' and an 'Out' directory. For the intermediate files, and the output files, respectively.

This obviously makes it easy to just go to your 'viewlocal' directory and do a simple delete, to get rid of everything.

Before you spent time figuring out a way to work around this with scripts, you might think about setting up something similar.

I won't lie though, maintaining such a setup in a large organization has proved....interesting. Especially when you use technologies such as QT that like to process files and create non-sourcecontrolled source files. But that is a whole OTHER story!

pj4533
  • 1,641
  • 3
  • 16
  • 38
-1

I think you can right click to your solution/project and click "Clean" button.

As far as I remember it was working like that. I don't have my VS.NET with me now so can't test it.

dr. evil
  • 25,988
  • 28
  • 126
  • 198
  • That's correct, and by far the most simple and easiest of all the suggested solutions (assuming it's appropriate to the specific situation....) – Chris Halcrow Aug 08 '13 at 05:18
  • 10
    Sorry, but this is simply not true. It does not delete the contents of /obj which are the root of the problem. At least this is the situation with VS 2013 update 3. – Ognyan Dimitrov Oct 27 '14 at 09:40
  • Just had the same problem with VS2013 update 4. (Note: VS2010 was doing fine) – juFo Mar 31 '15 at 07:33
  • See this answer (on this very same question) for a better explanation: http://stackoverflow.com/a/18317221/374198 – Josh M. Oct 22 '15 at 10:59