MSBuild task to recursively delete all of a folder's contents
Following the Perl mantra of TMTOWTDI - we had a question come up about how to recursively delete a folder's contents - without deleting the folder itself - using MSBuild.
There are several solutions, but if you have a lot of crud to delete, one of the faster ways is to create a target which has the following calls:
<Exec Command="dir /ad /b c:\Temp > files.txt"/>
<Exec Command='for /f "Tokens=*" %%i in (files.txt) do rd /s/q "C:\Temp\%%i"'/>
<Delete Files="files.txt"/>
This spits out all of the subfolders to a temporary text file, then deletes them by looping over them and calling rd. The reason you have to do it this way is that if you just use the for loop without the Tokens=* line, it won't find directories with spaces in the name, as it, by default, only reads in the first space delimited token.
The reason it has to be to calls is that the "dir /ad /b c:\Temp" call has to be in single-quotes in the for command, but the Tokens=* has to be in double quotes. Since one of those is already taken because we are in an XML attribute, you need to break it into two seperate calls.
Another way would be to break the commands into two seperate properties, and then exec that:
<PropertyGroup>
<dir_list>dir /ad /b c:\Temp</dir_list>
<del_command>for /f "Tokens=*" %%i in ('$(dir_list)') do rd /s/q "C:\Temp\%%i"</del_command>
</PropertyGroup>
<Target Name="DeleteTemp">
<Exec Command="$(del_command)"/>
</Target>




3 Comments:
Cory what about
<ItemGroup>
<SettingsFiles Include="$(ProgramFiles)\App\Settings\**"/>
</ItemGroup>
<Target Name="DeleteAppSettingsFiles">
<Delete Files="@(SettingsFiles)" />
</Target>
By
Anonymous, at 10:37 AM
or use the CleanFolder task in the Microsoft SDC Tasks Library: http://www.codeplex.com/sdctasks
By
FreeToDev, at 4:51 PM
Using that 'DeleteAppSettingsFiles' as is currently has two problems. 1. it will not delete read only files, 2. It will not delete the folders, only files.
The CleanFolder task provides an easy mechanism to do this.
By
Anonymous, at 4:40 AM
Post a Comment
Links to this post:
Create a Link
<< Home