Batch command to delete all subfolders with specific name having special character - batch-file

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"

Related

How to copy specific subfolders if existing to new folders in a backup folder using a batch file?

I am a total beginner and I need some help to backup some folders with files from a server.
I need to copy some folders to my local computer.
Folders to copy are like this
\\DistantServer\path\RandomFolder\Config\old
\\DistantServer\path\Another Random Folder\Config\old
...
Those old folders should be copied to:
D:\Backup\RandomFolder\old
D:\Backup\Another Random Folder\old
I tried some codes, but I'm only having errors.
Could anyone help me?
This batch file should work for the task:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "SourceFolder=\\DistantServer\path"
set "TargetFolder=D:\Backup"
for /D %%I in ("%SourceFolder%\*") do (
if exist "%%I\Config\Old\" (
rd /Q /S "%TargetFolder%\%%~nxI\old" 2>nul
%SystemRoot%\System32\xcopy.exe "%%I\Config\Old" "%TargetFolder%\%%~nxI\old\" /C /E /H /I /K /Q /R /Y >nul
)
)
endlocal
The command FOR searches in source folder as defined with environment variable SourceFolder for non hidden subfolders. Each subfolder found is assigned with full path not ending with a backslash and never enclosed in double quotes to loop variable I referenced with %%I.
The command IF checks for existence of the subfolder Config\old in current subfolder of source folder. The found subfolder is ignored if not containing the subfolder Config\old.
On existence of Config\old in current subfolder of source folder the command RD first removes quietly with all subfolders the appropriate target folder independent on its existence to make sure that the copy done next results in 1:1 folder copy. The RD command can be removed in case of target folder most likely never exists before the copying is done or if it is wanted that existing contents of target folder is merged with current contents of source folder.
%%~nxI references the current subfolder in source folder without path, i.e. without folder path as defined with environment variable SourceFolder.
The command XCOPY copies the entire folder Config\old in current subfolder of source folder to a subfolder old in target folder as defined by environment variable TargetFolder. The entire directory structure to appropriate target folder is automatically created by XCOPY if not already existing because of target specification ends with a backslash being a clear indication for XCOPY that the target string specifies a directory.
Note: The entire code above without command RD could be optimized also to a single command line.
#for /D %%I in ("\\DistantServer\path\*") do #if exist "%%I\Config\Old\" %SystemRoot%\System32\xcopy.exe "%%I\Config\Old" "D:\Backup\%%~nxI\old\" /C /E /H /I /K /Q /R /Y >nul
Single command line with command RD:
#for /D %%I in ("\\DistantServer\path\*") do #if exist "%%I\Config\Old\" rd /Q /S "D:\Backup\%%~nxI\old" 2>nul & %SystemRoot%\System32\xcopy.exe "%%I\Config\Old" "D:\Backup\%%~nxI\old\" /C /E /H /I /K /Q /R /Y >nul
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
echo /?
endlocal /?
for /?
if /?
rd /?
set /?
setlocal /?
xcopy /?
Read also the Microsoft article about Using Command Redirection Operators for an explanation of >nul and 2>nul. And read answer on Single line with multiple commands using Windows batch file for an explanation of operator & as used in the last batch code (single command line with RD).

how to delete subfolders without deleting parent folder and child folder?

For this type of directory structure:
\\rdwlhsdevserver\root\user1\folders\testdat.txt
\\rdwlhsdevserver\root\abhay\testdat.txt
\\rdwlhsdevserver\root\testuser\folders1\folder2\testdat.txt
\\rdwlhsdevserver\root\devadmin\input\testdat.txt
\\rdwlhsdevserver\root\admin\testdata\testdat.txt
I know that I can use del /s /q \\rdwlhsdevserver\root\* to delete files from parent folder and all sub-folders. But I want to delete all folders and files except \\rdwlhsdevserver\root\<folder>\.
After running cmd output should be like:
\\rdwlhsdevserver\root\user1\
\\rdwlhsdevserver\root\abhay\
\\rdwlhsdevserver\root\testuser\
\\rdwlhsdevserver\root\devadmin\
\\rdwlhsdevserver\root\admin\
pushd "\\rdwlhsdevserver\root" && (
for /d %%a in (*) do ( cd "%%a" && ( 2>nul rmdir . /s /q & cd .. ) )
del /f /q *
popd
)
This will change the current active directory (pushd) to the target directory and if there are no problems (conditional execution operator &&) for each folder (for /d) change to it (cd), remove its contents (rmdir) and return to the parent folder. Once done, remove (del) the files inside the root folder and restore the initial active directory.
Why not change the inner for to for /d %%a in (*) do rmdir "%%a" /s /q ? Because this will also remove the folder. But if we first make the folder the current active directory (cd) we will be able to delete its contents but not the folder itself as it is in use (the 2>nul is a redirection of the stderr stream to nul to hide the error in the rmdir saying it can not remove the folder because it is in use)
You need to iterate over all sub-directories of \\rdwlhsdevserver\root\ using a for /D loop, then loop over each sub-directory's sub-directories again by another for /D loop, then apply the rmdir (or rd) command on each of the returned items, like this:
for /D %%J in ("\\rdwlhsdevserver\root\*") do (
for /D %%I in ("%%~J\*") do (
rmdir /S /Q "%%~I"
)
)
Or in command prompt directly:
for /D %J in ("\\rdwlhsdevserver\root\*") do #for /D %I in ("%~J\*") do #rmdir /S /Q "%~I"
For the sake of overall performance, if you want to delete directories and files, I recommend to do the above directory removal before the file deletion (del /S /Q "\\rdwlhsdevserver\root\*"). Note that your del command line also deletes files located in the directory \\rdwlhsdevserver\root\.

Recursively find and delete a folder using batch file

I am trying to write a simple batch file which will recursively find and delete a folder. But the following script is not looking under sub folder. Wondering how to do that?
#echo off
cd /d "C:\"
for /d %%i in (temp) do rd /s "%%i"
pause
Thanks!
for /d /r "c:\" %%a in (temp\) do if exist "%%a" echo rmdir /s /q "%%a"
For each folder (/d), recursively (/r) under c:\ test for the presence of a temp folder and if it exist, remove it
directory removal command is only echoed to console. If the output is correct, remove the echo command
The /S switch to rd means
/S Removes all directories and files in the specified directory
in addition to the directory itself. Used to remove a directory
tree.
It does not mean it will search all directories looking for one with the specified name and delete them.
In other words, if you run rd /S Test from the C:\Temp folder, it will delete C:\Temp\Test\*.*, including all subdirectories (of any name) of C:\Temp\Test. It does not mean it will delete C:\Temp\AnotherDir\Test, because that isn't a subfolder of C:\Temp\Test.

Batch command to delete all subfolders with a specific name

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.

Batch file to delete folder but leave a certain subfolder?

I'm trying to clear a folder of all it's contents but a certain sub-folder and its contents. My deleting works fine but I can't figure out how to exclude.
cd C:\testfolder
del * /S /Q
rmdire /S /Q "C:\testfolder"
But I do not want to delete the folder C:\testfolder\subf. How can I do this?
If you are using at least windows vista (robocopy command is used), this should do the job
#echo off
setlocal enableextensions disabledelayedexpansion
rem Create a temporary empty folder
set "tempFolder=%temp%\%~nx0.%random%%random%%random%.tmp"
md "%tempFolder%" >nul 2>nul
rem Purge from target folder anything not in the empty source folder,
rem but exclude the indicated folder
robocopy "%tempFolder%" "c:\testfolder" /nocopy /purge /xd "c:\testfolder\subfolder"
rem Cleanup
rmdir "%tempFolder%" /s /q >nul 2>nul
If you mean you want to delete all files but not the subfolder you can just use the following
cd C:\testfolder
del *.* /S /Q
This will delete any files in the "testfolder" and any files in the subfolders but will leave the subfolder there.

Resources