I have a directory as such:
D:\Movies
D:\Movies\MovieTitle1\backdrops\
D:\Movies\MovieTitle2\backdrops\
D:\Movies\MovieTitle3\backdrops\
D:\Movies\MovieTitle4\backdrops\
How could I have a batch file delete all folders named "Backdrops"? I would prefer it to run recursive from just the D:\ drive if possible.
Short answer:
FOR /d /r . %%d IN (backdrops) DO #IF EXIST "%%d" rd /s /q "%%d"
I got my answer from one of the countless answers to the same question on Stack Overflow:
Command line tool to delete folder with a specified name recursively in Windows?
This command is not tested, but I do trust this site enough to post this answer.
As suggested by Alex in a comment, this batch script should be foolproof:
D:
FOR /d /r . %%d IN (backdrops) DO #IF EXIST "%%d" rd /s /q "%%d"
Above answer didn't quite work for me. I had to use a combination of #itd solution and #Groo comment. Kudos to them.
Final solution for me was (using the backdrop folder example):
FOR /d /r . %%d IN ("backdrops") DO #IF EXIST "%%d" rd /s /q "%%d"
I will open a different answer, because it would be too cramped in the comments. It was asked what to do, if you want to execute from/to a different folder and I want to give an example for non-recursive deletion.
First of all, when you use the command in cmd, you have to use %d, but when you use it in a .bat, you have to use %%d.
You can use a wildcard to just process folders that for example start with "backdrops": "backdrops*".
Recursive deletion of folders starting in the folder the .bat is in:
FOR /d /r . %d IN ("backdrops") DO #IF EXIST "%d" rd /s /q "%d"
Non-recursive deletion of folders in the folder the .bat is in (used with wildcard, as you cannot have more than one folder with the same name anyway):
FOR /d %d IN ("backdrops*") DO #IF EXIST "%d" rd /s /q "%d"
Recursive deletion of folders starting in the folder of your choice:
FOR /d /r "PATH_TO_FOLDER" %d IN ("backdrops") DO #IF EXIST "%d" rd /s /q "%d"
Non-recursive deletion of folders in the folder of your choice (used with wildcard, as you cannot have more than one folder with the same name anyway):
FOR /d %d IN ("PATH_TO_FOLDER/backdrops*") DO #IF EXIST "%d" rd /s /q "%d"
I look at this question from the .Net developer's point of view. Sometimes it is needed to wipe all */bin/ and */obj/ subfolders recursively starting from the directory from which the batch script is executed.
I tried abovementioned solutions and sighted a crutial point:
Unlike other variants of the FOR command you must include a wildcard (either * or ?) in the 'folder_set' to get consistent results returned.
Source: https://ss64.com/nt/for_d.html
When adding echo for each found result before deleting it we can ensure that there are no false positive matches. When I have done so, I found out that using (obj) folder_set without a wildcard triggers DO expression for each subfolder even if it doesn't match a mask. E.g. deleting the "/.git/objects/" dir which is bad. Adding a question mark (0 or 1 occurrence of any symbol except dot) at the end of the mask solves this issue:
#echo off
FOR /d /r %%F IN (obj?) DO (
echo deleting folder: %%F
#IF EXIST %%F RMDIR /S /Q "%%F"
)
FOR /d /r %%F IN (bin?) DO (
echo deleting folder: %%F
#IF EXIST %%F RMDIR /S /Q "%%F"
)
The same goes for any other masks. E.g. (packages?) and (node_modules?) to wipe cached libraries for making a backup archive more lightweight.
Related
I have a directory as such:
D:\DATA\DATA2\Demo&_1\Demo\1\deployment
D:\DATA\DATA2\Demo&_1\Demo\2\deployment
D:\DATA\DATA2\Demo&_1\Demo\3\deployment
And I am running the below batch file command to delete all deployment folders present inside Demo folder:
cd /d D:\DATA\DATA2\Demo&_1\Demo
FOR /d /r . %%d IN (deployment) DO #IF EXIST "%%d" rd /s /q "%%d"
The above command is not working(not deleting deployment folder) when I have special character in in folder name (Demo&_1) and when I have do not have special then it is working(deleting deployment folder).
For e.g. if I change name of folder "Demo&_1" to "Demo1" the above batch file will work fine but not work if have special character.
Simply because the paths are not in quotes, but regardless here is a much simpler solution without having to do cd /d
for /D /R "D:\DATA\DATA2\Demo&_1\Demo" %%d IN (deployment) DO #IF EXIST "%%d" rd /s /q "%%d"
I am currently working at my first Junior IT position, and I am having trouble with a simple batch file.
Essentially the file is ran weekly through the task scheduler. It removes files and folders from a server directory that are older than 8 days. It is also supposed to remove empty folders.
forfiles /p "P:\blahblah" /s /m * /d -8 /c "cmd /c del /Q /S /F /A #path"
cd /d P:\blahblah
for /f "usebackq" %%d in (`"dir /ad/b/s | sort /R"`) do rd "%%d"
REM robocopy "P:\blahblah" "P:\blahblah" /s /move"
There are two problems here;
It will occasionally delete files only a few days old.
It will not remove empty folders.
The file was written by an old junior IT employee and there is no documentation. My guess is multiple methods were used in order to ensure the cleanup (ironically). I have searched google and here are my current thoughts on each command..
1) forfiles - the forfiles command seems to be written correctly and I do not see any issues with it.
2) cd - simple enough
3) for - not entirely sure. The batch variables are new to me and I am not sure if it is working correctly.
4) robocopy - I have not been able to find an instance online where someone copies a directory to itself for cleanup. I also notice the extra quotation in there, but i am not certain of its incorrectness. This line especially seems odd to me.
Normally I would try and test my through something like this, but It is a bit harder to test quickly given I need to see if it is removing things based on calendar date. That's why I am here!
I promise I would not have asked if I had not already scoured the internet for an idea. Any help would be greatly appreciated, and I would love to learn a little more about the above commands!
Thanks for your help!
forfiles
Being syntactically correct doesn't mean it does what you want, it does what you ask. Here the problem is the del command. It will delete what the forfiles has selected, but you should test the selected element is not a folder. If you call del /q /s /f /a with a folder reference, you delete the folder contents.
cd
Simple enough, but as you don't check the operation was sucessful (maybe P: is not available) maybe the following for command removes information where it should not.
for
As Squashman comments, if you change the back quotes into single quotes you will not need the usebackq.
But you need the delims clause to avoid problems with paths containing spaces. for /f does not iterate over file references, but over lines of text (in this case generated by a dir command). By default tabs and spaces are delimiters that split the lines being processed and, also by default, only the first token is retrieved. Setting the delims clause to an empty list of characters will disable this behaviour.
You can try with something like
#echo off
setlocal enableextensions disabledelayedexpansion
pushd "p:\blahblah" && (
forfiles /s /m * /d -8 /c "cmd /c if #isdir==FALSE del /q /f /a #path"
for /f "delims=" %%d in ('" dir /ad /s /b | sort /R "') do rd "%%d"
popd
)
The pushd will change the current active directory to the required one. If the command is sucessful, the conditional operator && (execute next command if the previous one did not fail) will execute the rest of the code, restoring the active directory at the end.
4) robocopy
It can be used to do the clean, but not from a folder into itself.
#echo off
setlocal enableextensions disabledelayedexpansion
pushd "p:\blahblah" && (
rem Use a random temporary folder
for %%t in ("%temp%\clean_%random%%random%%random%%random%.tmp") do (
rem Select the files to keep
robocopy "." "%%~ft" /MAXAGE:8 /CREATE /s /njh /njs /nfl /nc /ns
rem Remove anything not selected
robocopy "%%~ft" "." /NOCOPY /PURGE /e /njh /njs /nfl /nc /ns
rem remove temporary folder
) & rd /s /q "%%~ft"
rem Restore previous active directory
popd
)
This code creates a replica of all the selected files (not older than 8 days) into a temporary folder, but the /CREATE switch tells robocopy to not copy the files, but to create 0 bytes files into the temporary target.
Once we have a replica with only the selected elements, the oposite operation is done, from temporary folder into work folder but requesting that no copy operation should be done (/NOCOPY), just a removal of elements not present in source (/PURGE).
I need to copy a folder matching a wildcard, for instance FOLDER_*. That folder will be in the presence of other files, so I need the command to segregate it from everything else. Also, the command needs to recursively search through the directory, and return only the FOLDER that matches the wildcard, with its contents intact. Then it needs to copy it to another folder. Any ideas? I've tried quite a few variants - here is the last thing I tried.
for /D /R %%f in (FOLDER_*) do xcopy %%f %~dp0\TestResults
Next code snippet should copy all found FOLDER_* folders including their subfolders but omits all their parent folder(s) like upfolder\ in upfolder\FOLDER_* (however could be improved to include it, of course).
for /F loop against dir /b /s /ad (a static list of subfolders) is used instead of for /D /R as the option /d /r is undocumented.
Pay your attention to recursion like FOLDER_main\FOLDER_sub1\FOLDER_sub11 etc.
Operational mkdir and xcopy commands are merely echoed for debugging purposes only:
#echo OFF
for /F "delims=" %%f in ('dir /B /S /AD FOLDER_*') do (
echo mkdir "%~dp0\TestResults\%%~nxf" 2>NUL
echo xcopy /S /E /C "%%~ff" "%~dp0\TestResults\%%~nxf\"
)
Consider adding more switches to xcopy, for instance
/H Copies hidden and system files also.
/R Overwrites read-only files.
/Y Suppresses prompting to confirm you want to overwrite an existing destination file.
I have a file structure of images that is fairly flat although quite large (only goes 3-4 levels deep). In this structure I want to delete all folders that end with '.files' (no quotes).
Note that the files I want to delete are hidden.
I saw a relevant question (linked below) that suggested the following batch file (except using '_svn')
Command line tool to delete folder with a specified name recursively in Windows?
for /d /r . %d in (_svn) do #if exist "%d" rd /s/q "%d"
but it didnt work quite right for me. I got the following error when running at the directory I want to start:
d" rd /s/q "d" was unexpected at this time.
So to be clear, I'm looking for a command that I can put into a batch file which I can cd to my desired directory, run the command, and delete directories beneath the current directory that end in '.files'
Any suggestions?
for /f %a in ('dir C:\yourdir\*.files /b /s /a:hd') do rd /s /q "%a"
or if running it from a batch file use 2 %'s
for /f %%a in ('dir C:\yourdir\*.files /b /s /a:hd') do rd /s /q "%%a"
In order to delete all ".svn" files/folders/subfolders in "myfolder" I use this simple line in a batch file:
FOR /R myfolder %%X IN (.svn) DO (RD /S /Q "%%X")
This works, but if there are no ".svn" files/folders the batch file shows a warning saying: "The system cannot find the file specified."
This warning is very noisy so I was wondering how to make it understand that if it doesn't find any ".svn" files/folders he must skip the RD command.
Usually using wild cards would suffice, but in this case I don't know how to use them, because I don't want to delete files/folders with .svn extension, but I want to delete the files/folders named exactly ".svn", so if I do this:
FOR /R myfolder %%X IN (*.svn) DO (RD /S /Q "%%X")
it would NOT delete files/folders named exactly ".svn" anymore.
I tried also this:
FOR /R myfolder %%X IN (.sv*) DO (RD /S /Q "%%X")
but it doesn't work either, he deletes nothing.
you can try
FOR /R myfolder %%X IN (.svn) DO (RD /S /Q "%%X" 2>nul)
for /f "tokens=* delims=" %%i in ('dir /s /b /a:d *svn') do (rd /s /q "%%i")
Something like that using find :
rm -rf `find . -name ".svn" -type d`
Edit:
I know this is for linux (I read bash instead of batch). I'm leaving it here to help Linux users that would randomly end-up here :)
Actually, this answer is from Jesper Rønn-Jensen at
http://justaddwater.dk/2011/03/01/easy-delete-all-svn-subfolders-in-windows-explorer/
I thought it was so much easier I'd share. I'm converting several projects from .SVN to .GIT, so this was great. It adds a menu item to Explorer so you can remove the folders. Create a .reg file, and import it.
Windows Registry Editor Version 5.00
;
; Running this file will give you an extra context menu item in Windows Explorer
; "Delete SVN folders"
;
; For the selected folder, it will remove all subfolders named ".svn" and their content
; Tip from http://www.iamatechie.com/remove-all-svn-folders-in-windows-xp-vista/
;
; Enrichened with comments by Jesper Rønn-Jensen ( http://justaddwater.dk/ )
;
;
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\DeleteSVN]
#="Delete SVN Folders"
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\DeleteSVN\command]
#="cmd.exe /c \"TITLE Removing SVN Folders in %1 && FOR /r \"%1\" %%f IN (.svn) DO RD /s /q \"%%f\" \""
Bizarre sidenote: if I use
FOR /R . %%X IN (*.svn) DO (echo "%%X")
instead of
FOR /R myfolder %%X IN (.svn) DO (RD /S /Q "%%X")
not only does it list all directories ending in .svn, it lists ALL THEIR CONTENTS as well. This is a BUG in the For command, it gave me an expansion where I gave it no wild card. Very strange.
Ken
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. Your 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.
Here is my favorite, its simple and compact:
find ./ -name ".svn" | xargs rm -Rf
Fissh
To delete all svn files on windows
for /d /r . %d in (.svn) do #if exist "%d" rd /s/q "%d"
.svn is the folder name