Command to recursively remove all .svn directories on Windows - windows

I have a directory with many sub-directories. In each folder there is a subversion folder (.svn).
Is there a command in windows that will go through each folder and sub-directory and delete the .svn folder?
Or will I have to create a script or do it manually?

Make a litte batch file with the following line and execute it from the parent folder under which there are .svn directories.
FOR /F "tokens=*" %%G IN ('DIR /B /AD /S *.svn*') DO RMDIR /S /Q "%%G"
You can also issue the line below straight from the Command Prompt:
FOR /F "tokens=*" %G IN ('DIR /B /AD /S *.svn*') DO RMDIR /S /Q "%G"

Do this in PowerShell.
NOTE: This is recursive so be sure you are in the right directory!
gci -fil '.svn' -r -force | ri -r -force
Here is the rest of my source tree cleanup script.
gci -fil 'bin' -r -force | ri -r -force
gci -fil 'obj' -r -force | ri -r -force
gci -fil '_ReSharper*' -r -force | ri -r -force
gci -fil '*.suo' -r -force | ri -r -force
gci -fil '*.user' -r -force | ri -r -force

Use the svn export command to export a Subversion working copy into a new "clean" directory structure that doesn't have the .svn directories.

If you want to delete all sub folders named .svn in windows
then create batch file with this content:
for /f "tokens=* delims=" %%i in ('dir /s /b /a:d *.svn') do (
rd /s /q "%%i"
)
save it in a file del_All_Dot_SVN_Folders.cmd . Run it. You're done.
Thanks to http://www.axelscript.com/2008/03/11/delete-all-svn-files-in-windows/
Remember the above code has .svn whereas the code in the link has only *svn so its better
to have the .svn to not accidentally have undesired effect.

Just type .svn in the search box of the File Explorer, then select and delete all search results (see JB Nizet's comment). This method can of course also be used to quickly delete the obj and bin directories, e.g. when organizing svn archives.
Although OP asked for a commandline solution, he also indicated using Windows, and considered a manual deletion, so the File Explorer method could still be considered, especially because it is the fastest method and does not rely on 'tools' like svn export.
Although OP already selected an accepted answer, this answer might still be useful for others. At least it was useful for me, a long time linux / windows user who prefers command lines and first learned about the search box by this post :-)

Sorry for being late to the party but here's another one in a single line:
for /r %i in (.svn) do rmdir /s /q "%i"

I know its too late to answer this but i guess there is an easy way IF have eclipse and the svn plugin installed on your eclipse. Right click on the project, go to Team->disconnect. It will open a popup where you select the first option: 'Also delete the SVN meta-information from file system.' This will remove all the SVN folders automatically along with svn property files that you might forget sometimes while removing .svn folders only!

As an important point, if you want to run shell to delete .svn folders, you may need -depth argument to prevent find command entering the directory that was just deleted and showing silly error messages like e.g.
"find: ./.svn: No such file or directory"
To get rid of this error, you can use the find command as the following:
cd [dir_to_delete_svn_folders]
find . -depth -name .svn -exec rm -fr {} \;

Related

How to add empty folders when importing from SVN to Git under Windows?

I need to migrate multiple repositories from SVN to Git under Windows. Part of the repositories has empty folders, they are critical for projects and these folders cannot be deleted without breaking the project.
I tried the git svn clone command with the keys --preserve-empty-dirs --placeholder-filename = .gitkeep but this does not work at all.
As a result, the folder is not added to the commit history - this is a big problem because it is impossible to updade to the old version. After full migration the folder is also not added.
I tried to make a crutch to the mechanism, but I do not understand how to make it correctly:
This code creates zero-size files that Git does not process:
for /f "delims=" %d in ('dir /s /b /ad ^| sort /r') do (fsutil file createnew %d/.gitkeep 0 && echo.>%%d/.gitkeep)
This code creates files with a size of 2 bytes:
for /f "delims=" %d in ('dir /s /b /ad ^| sort /r') do (echo.>%d/.gitkeep)
In both cases, there is a problem with the fact that files are created in all folders, and not just empty ones. In addition, I lack an understanding of how to exclude the .git folder from processing.
Please, help.
No way, but I wrote a crutch under Ubuntu 18.04, it works successfully in WSL:
echo The crutches for git svn clone --preserve-empty-dirs command, because it is not working properly.
find . -type d -empty -not -path "./.git/*" -exec echo blablabla>.gitkeep \;
git add --all

How to solve "The directory is not empty" error when running rmdir command in a batch script?

I am making a batch script and part of the script is trying to remove a directory and all of its sub-directories. I am getting an intermittent error about a sub-directory not being empty. I read one article about indexing being the culprit. I disabled WSearch but I eventually got the error again. Here's the command:
rmdir /S /Q "C:\<dir>\"
I experienced the same issues as Harry Johnston has mentioned. rmdir /s /q would complain that a directory was not empty even though /s is meant to do the emptying for you! I think it's a bug in Windows, personally.
My workaround is to del everything in the directory before deleting the directory itself:
del /f /s /q mydir 1>nul
rmdir /s /q mydir
(The 1>nul hides the standard output of del because otherwise, it lists every single file it deletes.)
I'm familiar with this problem. The simplest workaround is to conditionally repeat the operation. I've never seen it fail twice in a row - unless there actually is an open file or a permissions issue, obviously!
rd /s /q c:\deleteme
if exist c:\deleteme rd /s /q c:\deleteme
I just encountered the same problem and it had to do with some files being lost or corrupted. To correct the issue, just run check disk:
chkdsk /F e:
This can be run from the search windows box or from a cmd prompt. The /F fixes any issues it finds, like recovering the files. Once this finishes running, you can delete the files and folders like normal.
enter the Command Prompt as Admin and run
rmdir /s <FOLDER>
I had a similar problem, tried to delete an empty folder via windows explorer. Showed me the not empty error, so I thought I try it via admin cmd, but none of the answers here helped.
After I moved a file into the empty folder. I was able to delete the non empty folder
As #gfullam stated in a comment to #BoffinbraiN's answer, the <dir> you are deleting itself might not be the one which contains files: there might be subdirectories in <dir> that get a "The directory is not empty" message and the only solution then would be to recursively iterate over the directories, manually deleting all their containing files... I ended up deciding to use a port of rm from UNIX. rm.exe comes with Git Bash, MinGW, Cygwin, GnuWin32 and others. You just need to have its parent directory in your PATH and then execute as you would in a UNIX system.
Batch script example:
set PATH=C:\cygwin64\bin;%PATH%
rm -rf "C:\<dir>"
Im my case i just moved the folder to root directory like so.
move <source directory> c:\
And then ran the command to remove the directory
rmdir c:\<moved directory> /s /q
I had "C:\Users\User Name\OneDrive\Fonts", which was mklink'ed ( /D ) to "C:\Windows\Fonts", and I got the same problem. In my case
cd "C:\Users\User Name\OneDrive"
rd /s Fonts
Y (to confirm the action)
helped me. I hope, that it helps you too ;D
What worked for me is the following. I appears like the RMDir command will issue “The directory is not empty” nearly all the time...
:Cleanup_Temporary_Files_and_Folders
Erase /F /S /Q C:\MyDir
RMDir /S /Q C:\MyDir
If Exist C:\MyDir GoTo Cleanup_Temporary_Files_and_Folders
The reason rd /s refuses to delete certain files is most likely due to READONLY file attributes on files in the directory.
The proper way to fix this, is to make sure you reset the attributes on all files first:
attrib -r %directory% /s /d
rd /s %directory%
There could be others such as hidden or system files, so if you want to play it safe:
attrib -h -r -s %directory% /s /d
rd /s %directory%
Windows sometimes is "broken by design", so you need to create an empty folder, and then mirror the "broken folder" with an "empty folder" with backup mode.
robocopy - cmd copy utility
/copyall - copies everything
/mir deletes item if there is no such item in source a.k.a mirrors source with
destination
/b works around premissions shenanigans
Create en empty dir like this:
mkdir empty
overwrite broken folder with empty like this:
robocopy /copyall /mir /b empty broken
and then delete that folder
rd broken /s
rd empty /s
If this does not help, try restarting in "recovery mode with command prompt" by holding shift when clicking restart and trying to run these command again in recovery mode
one liner:
if exist folder rmdir /Q /S folder
I'm using this in a NPM script like so (Javascript) :
//package.json
"scripts": {
"start": "parcel --no-cache",
"clean": "if exist dist rmdir /Q /S dist",
"deploy": "npm run clean && parcel build --no-source-maps && firebase deploy"
},
Open CMD as administrator
chkdsk c: /F /R
Press the “Y” key if asked to check your disk the next time your system restarts.
Restart the machine. After that just delete the folder.
The easiest way I found to do this is:
rm -rf dir_name
it worked on zsh - macOS, it should work on windows cmd as well.
if you need to delete a folder on Windows with a batch file you will need to use PowerShell and this is how it is done:
rmdir .\directory_name\ -Recurse
Similar to Harry Johnston's answer, I loop until it works.
set dirPath=C:\temp\mytest
:removedir
if exist "%dirPath%" (
rd /s /q "%dirPath%"
goto removedir
)
Force delete the directory (if exists)
Delete.bat
set output_path="C:\Temp\MyFolder"
if exist %output_path% (
echo Deleting %output_path%
attrib -r /s /d %output_path%
rd /s /q %output_path%
)
I've fixed this before my making sure there wasn't extra whitespace in the name of the directory I was deleting. This is more of a concern when I had the directory name contained within a variable that I was passing to RD. If you're specifying your directly in quotes then this isn't helpful, but I hope that someone like me comes along with the same problem and sees this. RD /S /Q can work, as I noticed the issue started happening when I changed something in my batch script.
I can think of the following possible causes:
there are files or subdirectories which need higher permissions
there are files in use, not only by WSearch, but maybe by your virus scanner or anything else
For 1.) you can try runas /user:Administrator in order to get higher privileges or start the batch file as administrator via context menu. If that doesn't help, maybe even the administrator doesn't have the rights. Then you need to take over the ownership of the directory.
For 2.) download Process Explorer, click Find/Find handle or DLL... or press Ctrl+F, type the name of the directory and find out who uses it. Close the application which uses the directory, if possible.

I want to delete all bin and obj folders to force all projects to rebuild everything

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?
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!
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 }
Or more terse:
gci -include bin,obj -recurse | remove-item -force -recurse
I thought I'd share, considering that I did not find the answer when I was looking here.
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
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.
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
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.
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://learn.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
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>
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
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 }
This is my batch file that I use for deleting all BIN and OBJ folders recursively.
Create an empty file and name it DeleteBinObjFolders.bat
Copy-paste code the below code into the DeleteBinObjFolders.bat
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
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
Several solutions above give answers how to exclude folders, but not in cmd. Expanding on Steve Willcock's answer, to exclude e.g. the node_modules folder, that may have bin folders in it, one can use the expanded one-liner below.
FOR /F "tokens=*" %G IN ('DIR /B /AD /S bin obj ^|find ^"node_modules^" /v /i') DO RMDIR /S /Q "%G"
As noted by others, in the case of putting the above command in a cmd script and not using it directly in the command line, substitute %G with %%G.
In VS 2019/VS 2022 this is the only sane solution.
In the solution folder (where the .sln file is located), create a file called Directory.Build.props and add edit it as shown below. Read about this special file here.
Directory.Build.props
<Project>
<Target Name="RemoveObjAndBinFolders" AfterTargets="Clean">
<PropertyGroup>
<ObjFolder>$(ProjectDir)$(BaseIntermediateOutputPath)</ObjFolder>
<BinFolder>$(ProjectDir)$(BaseOutputPath)</BinFolder>
<!-- Microsoft.NET.Sdk.Web sets $(BaseIntermediateOutputPath) to -->
<!-- an absolute path. Not fixed up to MsBuild 17! -->
<BaseIntermediateOutputPathFix Condition="$(BaseIntermediateOutputPath.StartsWith($(MSBuildProjectDirectory)))">$([MSBuild]::MakeRelative(
$(ProjectDir),
$(BaseIntermediateOutputPath)
))</BaseIntermediateOutputPathFix>
<ObjFolder Condition="$(BaseIntermediateOutputPath.StartsWith($(MSBuildProjectDirectory)))">$(ProjectDir)$(BaseIntermediateOutputPathFix)</ObjFolder>
</PropertyGroup>
<ItemGroup>
<ObjFiles Include="$(ObjFolder)/*.*"
Exclude="$(ObjFolder)/project.assets.json" />
<ObjSubFolders
Include="$([System.IO.Directory]::GetDirectories('$(ObjFolder)'))" />
</ItemGroup>
<!-- Remove "obj" sub folders -->
<RemoveDir Directories="#(ObjSubFolders)" ContinueOnError="true" />
<!-- Remove "obj" files (keeping necessary asset file)-->
<Delete Files="#(ObjFiles)" />
<!-- Remove "bin" folders -->
<RemoveDir Directories="$(BinFolder)" ContinueOnError="true" />
</Target>
</Project>
No need to modify a bunch of .csproj files. Also, note that I'm not removing $(TargetDir) as some have suggested. Doing so might cripple the build system if $(OutDir) has been set to some custom directory (a common thing to do).
Have a look at the CleanProject, it will delete bin folders, obj folders, TestResults folders and Resharper folders. The source code is also available.
from Using Windows PowerShell to remove obj, bin and ReSharper folders
very similar to Robert H answer with shorter syntax
run powershell
cd(change dir) to root of your project folder
paste and run below script
dir .\ -include bin,obj,resharper* -recurse | foreach($) { rd $_.fullname –Recurse –Force}
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.
Is 'clean' not good enough? Note that you can call msbuild with /t:clean from the command-line.
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.
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)"
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
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.
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!
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 }
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)
2. DIR /S /AD /B *obj will contain the result which is not expected (tobj folder)
This Works Fine For Me:
start for /d /r . %%d in (bin,obj, ClientBin,Generated_Code) do #if exist "%%d" rd /s /q "%%d"
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"
I took a different approach to this problem. Rather than write a script to hunt for all the "obj" and "bin" folders in various places, I direct the build process to group those folders in a single, convenient location.
Add a Directory.Build.props file to the solution folder like so:
<Project>
<PropertyGroup>
<BaseProjectArtifactPath>$(MSBuildThisFileDirectory).artifacts\$(MSBuildProjectName)</BaseProjectArtifactPath>
<BaseOutputPath>$(BaseProjectArtifactPath)\bin\</BaseOutputPath>
<BaseIntermediateOutputPath>$(BaseProjectArtifactPath)\obj\</BaseIntermediateOutputPath>
</PropertyGroup>
</Project>
Now, all of the "bin" & "obj" folders will be created in a separate .artifacts folder in the solution root, rather than the various project folders. Ready to start with a clean slate? Just delete the .artifacts folder and you're good to go.
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.

Command line tool to delete folder with a specified name recursively in Windows?

I want to delete every "_svn" in every folder and subfolder...
For example
c:\
proyect1
_svn
images
_svn
banner
_svn
buttons
_svn
Then I run something like
rm-recurse c:\proyect1 _svn
And I should get:
c:\
proyect1
images
banner
buttons
The ideal thing would be a tiny stand-alone EXE or something like that.
--
Thanks Grant, as soon as I posted the question I saw SVN documentation about the SVN export command, but I also want to delete the _vti_* folders stuff Visual Studio creates, so I'll also explore the for solution.
Similar to BlackTigerX's "for", I was going to suggest
for /d /r . %d in (_svn) do #if exist "%d" rd /s/q "%d"
Time to learn some PowerShell ;o)
Get-ChildItem -path c:\projet -Include '_svn' -Recurse -force | Remove-Item -force -Recurse
The first part finds each _svn folder recursively. Force is used to find hidden folders.
Second part is used to delete these folders and their contents.
Remove commandlet comes with a handy "whatif" parameter which allows to preview what will be done.
PowerShell is available for Windows XP and Windows Vista. It is present on Windows 7 and on Windows Server 2008 R2 by default.
It's a MS product, it's free, and it rocks!
For inclusion/invocation from within a BATCH file use (say for removing Debug and Release folder):
for /d /r . %%d in (Debug Release) do #if exist "%%d" echo "%%d" && rd /s/q "%%d"
double % are required within a batch file to work as escape chars. Else it reports error of syntax.
Thanks.
for /f "usebackq" %d in (`"dir _svn /ad/b/s"`) do rd /s/q "%d"
http://ebersys.blogspot.com/2008/07/recursively-delete-svn-folders-easy-way.html
In Windows? If you are using tortoiseSVN you can use the export command to export a copy of the project without the .svn/_svn folders.
import os
import shutil
curdir = os.path.abspath(os.path.dirname(__file__))
def removedir(dirname, name = ".svn"):
if os.path.isdir(dirname):
for file in os.listdir(dirname):
if os.path.isdir(os.path.join(dirname, file)) and file == name:
thedir = os.path.join(dirname, name)
shutil.rmtree(thedir)
print ".",
else:
removedir(os.path.join(dirname, file))
I think you can try this Python script, which will work under any OS if you've got Python installed.
Here... with FreeCommander or TotalCommander
http://www.broobles.com/blog/posts/36
socendani
Another option from SVN Forum: use XCopy with a file that contains the list of files/directories to be excluded (.svn or _svn in this case)
XCopy C:\VersionedFolder C:\UnVersionedFolder /EXCLUDE:C:\No.SVN.txt /E /C /I /F /R /Y

"rm -rf" equivalent for Windows?

I need a way to recursively delete a folder and its children.
Is there a prebuilt tool for this, or do I need to write one?
DEL /S doesn't delete directories.
DELTREE was removed from Windows 2000+
RMDIR or RD if you are using the classic Command Prompt (cmd.exe):
rd /s /q "path"
RMDIR [/S] [/Q] [drive:]path
RD [/S] [/Q] [drive:]path
/S Removes all directories and files in the specified directory in addition to the directory itself. Used to remove a directory tree.
/Q Quiet mode, do not ask if ok to remove a directory tree with /S
If you are using PowerShell you can use Remove-Item (which is aliased to del, erase, rd, ri, rm and rmdir) and takes a -Recurse argument that can be shorted to -r
rd -r "path"
admin:
takeown /r /f folder
cacls folder /c /G "ADMINNAME":F /T
rmdir /s folder
Works for anything including sys files
EDIT: I actually found the best way which also solves file path too long problem as well:
mkdir \empty
robocopy /mir \empty folder
RMDIR [/S] [/Q] [drive:]path
RD [/S] [/Q] [drive:]path
/S Removes all directories and files in the specified directory in addition to the directory itself. Used to remove a directory tree.
/Q Quiet mode, do not ask if ok to remove a directory tree with /S
Go to the path and trigger this command.
rd /s /q "FOLDER_NAME"
/s : Removes the specified directory and all subdirectories including any files. Use /s to remove a tree.
/q : Runs rmdir in quiet mode. Deletes directories without confirmation.
/? : Displays help at the command prompt.
You can install cygwin, which has rm as well as ls etc.
For deleting a directory (whether or not it exists) use the following:
if exist myfolder ( rmdir /s/q myfolder )
rm -r -fo <path>
is the closest you can get in Windows PowerShell. It is the abbreviation of
Remove-Item -Recurse -Force -Path <path>
(more details).
The accepted answer is great, but assuming you have Node installed, you can do this much more precisely with the node library "rimraf", which allows globbing patterns. If you use this a lot (I do), just install it globally.
yarn global add rimraf
then, for instance, a pattern I use constantly:
rimraf .\**\node_modules
or for a one-liner that let's you dodge the global install, but which takes slightly longer for the the package dynamic download:
npx rimraf .\**\node_modules
via Powershell
Remove-Item -Recurse -Force "TestDirectory"
via Command Prompt
https://stackoverflow.com/a/35731786/439130
Try this command:
del /s foldername
rmdir /S /Q %DIRNAME%
rmdir /s dirname
First, let’s review what rm -rf does:
C:\Users\ohnob\things>touch stuff.txt
C:\Users\ohnob\things>rm -rf stuff.txt
C:\Users\ohnob\things>mkdir stuff.txt
C:\Users\ohnob\things>rm -rf stuff.txt
C:\Users\ohnob\things>ls -l
total 0
C:\Users\ohnob\things>rm -rf stuff.txt
There are three scenarios where rm -rf is commonly used where it is expected to return 0:
The specified path does not exist.
The specified path exists and is a directory.
The specified path exists and is a file.
I’m going to ignore the whole permissions thing, but nobody uses permissions or tries to deny themselves write access on things in Windows anyways (OK, that’s meant to be a joke…).
First set ERRORLEVEL to 0 and then delete the path only if it exists, using different commands depending on whether or not it is a directory. IF EXIST does not set ERRORLEVEL to 0 if the path does not exist, so setting the ERRORLEVEL to 0 first is necessary to properly detect success in a way that mimics normal rm -rf usage. Guarding the RD with IF EXIST is necessary because RD, unlike rm -f, will throw an error if the target does not exist.
The following script snippet assumes that DELPATH is prequoted. (This is safe when you do something like SET DELPATH=%1. Try putting ECHO %1 in a .cmd and passing it an argument with spaces in it and see what happens for yourself). After the snippet completes, you can check for failure with IF ERRORLEVEL 1.
: # Determine whether we need to invoke DEL or RD or do nothing.
SET DELPATH_DELMETHOD=RD
PUSHD %DELPATH% 2>NUL
IF ERRORLEVEL 1 (SET DELPATH_DELMETHOD=DEL) ELSE (POPD)
IF NOT EXIST %DELPATH% SET DELPATH_DELMETHOD=NOOP
: # Reset ERRORLEVEL so that the last command which
: # otherwise set it does not cause us to falsely detect
: # failure.
CMD /C EXIT 0
IF %DELPATH_DELMETHOD%==DEL DEL /Q %DELPATH%
IF %DELPATH_DELMETHOD%==RD RD /S /Q %DELPATH%
Point is, everything is simpler when the environment just conforms to POSIX. Or if you install a minimal MSYS and just use that.
Here is what you need to do...
Create a batch file with the following line
RMDIR /S %1
Save your batch file as Remove.bat and put it in C:\windows
Create the following registry key
HKEY_CLASSES_ROOT\Directory\shell\Remove Directory (RMDIR)
Launch regedit and update the default value HKEY_CLASSES_ROOT\Directory\shell\Remove Directory (RMDIR)\default
with the following value
"c:\windows\REMOVE.bat" "%1"
Thats it! Now you can right click any directory and use the RMDIR function
LATE BUT IMPORTANT ANSWER to anyone who is having troubles installing npm packages on windows machine and if you are seeing error saying "rm -rf..." command not found.
You can use the bash cli to run rm command on windows.
for npm users, you can change the npm's config to npm config set script-shell "C:\Program Files\Git\bin\bash.exe" this way if the npm package you are trying to install has a post install script that uses rm -rf command, you will be able to run that rm command without needing to change anything in the npm package or disabling the post install scripts config. (For example, styled-components uses rm command in their post install scripts)
If you want to just use the rm command, you can easily use the bash and pass the arguments.
So yes, you can use the 'rm' command on windows.
As a sidenode:
From the linux version with all subdirs (recursive) + force delete
$ rm -rf ./path
to PowerShell
PS> rm -r -fo ./path
which has the close to same params (just seperated) (-fo is needed, since -f could match different other params)
note:
Remove-Item ALIASE
ri
rm
rmdir
del
erase
rd
in powershell, rm is alias of Remove-Item, so remove a file,
rm -R -Fo the_file
is equivalent to
Remove-Item -R -Fo the_file
if you feel comfortable with gnu rm util, you can the rm util by choco package manager on windows.
install gnu utils in powershell using choco:
choco install GnuWin
finally,
rm.exe -rf the_file
You can install GnuWin32 and use *nix commands natively on windows. I install this before I install anything else on a minty fresh copy of windows. :)
Using Powershell 5.1
get-childitem *logs* -path .\ -directory -recurse | remove-item -confirm:$false -recurse -force
Replace logs with the directory name you want to delete.
get-childitem searches for the children directory with the name recursively from current path (.).
remove-item deletes the result.
USE AT YOUR OWN RISK. INFORMATION PROVIDED 'AS IS'. NOT TESTED EXTENSIVELY.
Right-click Windows icon (usually bottom left) > click "Windows PowerShell (Admin)" > use this command (with due care, you can easily delete all your files if you're not careful):
rd -r -include *.* -force somedir
Where somedir is the non-empty directory you want to remove.
Note that with external attached disks, or disks with issues, Windows sometimes behaves odd - it does not error in the delete (or any copy attempt), yet the directory is not deleted (or not copied) as instructed. (I found that in this case, at least for me, the command given by #n_y in his answer will produce errors like 'get-childitem : The file or directory is corrupted and unreadable.' as a result in PowerShell)
In powershell rm -recurse -force works quite well.
here is what worked for me:
Just try decreasing the length of the path.
i.e :: Rename all folders that lead to such a file to smallest possible names. Say one letter names. Go on renaming upwards in the folder hierarchy.
By this u effectively reduce the path length.
Now finally try deleting the file straight away.
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\Folder\shell\rmdir\command]
#="cmd.exe /s /c rmdir "%V""
There is also deltree if you're on an older version of windows.
You can learn more about it from here:
SS64: DELTREE - Delete all subfolders and files.

Resources