copying all the elements of a folder into another folder using a loop in batch file - windows

I want to copy all the files of a folder into some other folders using batch script. Say, I have two folders named folder1 and folder2. these two folders are located in C:\Users\xyz . I want to copy the elements of another folder (say, folder3 which is located in C:\Users\abc\def) into these two folders. I have made the following script but nothing is copied. My sample batch file is as follows:
FOR /L %%A IN (1,1,2) DO (
xcopy /s C:\Users\abc\def\folder3 C:\Users\xyz\folder%%A
)
is there anything wrong in the batch file?

xcopy /s C:\Users\abc\def\folder3\*.* C:\Users\xyz\folder%%A\
where *.* is an appropriate filemask and the final \ in the destination name tells cmd that the destination is a directory.

I suggest using this command line in the batch file:
for /L %%A in(1,1,2) do %SystemRoot%\System32\xcopy.exe "C:\Users\abc\def\folder3" "C:\Users\xyz\folder%%A\" /C /G /H /I /K /R /Q /S /Y >nul
I enclosed both directory paths in double quotes in case of real paths contain 1 or more spaces or other special characters which require double quotes. The last paragraph on last help page output by running in a command prompt window cmd /? outputs on which characters in a directory/file name double quotes are required around the complete directory/file name.
The target path ends with a backslash to make it clear for console application xcopy that the target is a directory and not a file. Together with the redundant /I the target directory is created if not existing already.
For details on the options used on xcopy open a command prompt window and run xcopy /?. This outputs the help for this console application in the command prompt window. On Windows running a command or console application with /? as parameter outputs in general the help for the command/application.
Note: The copying from one user profile directory to another user profile directory requires local administrator privileges. Each user profile directory is by default protected for exclusive usage of the owning user. Therefore I suggest to open a command prompt window and execute in this window:
for /L %A in(1,1,2) do %SystemRoot%\System32\xcopy.exe "C:\Users\abc\def\folder3" "C:\Users\xyz\folder%A\" /C /G /H /I /K /R /S /Y
You can see if that works with just %A as required on command line instead of %%A as required in batch files and without /Q (quiet copying) and without >nul (redirection of success messages to device NUL to suppress them). Or when it does not work, you can see why it does not work as the error message can be viewed on running a command or a batch file from within a command prompt window instead of double clicking on a batch file because the console window keeps open.

Related

Batch Script to copy files from a Text file

I need help with below code as it is executing in root folder only whereas I want the code to look for files within sub folders as well.
for /F "tokens=*" %%A in (documents.txt) do (
copy %%A E:\Destination\
)
I suggest to use this command line in the batch file to copy all files with duplicating directory structure from source to destination directory.
for /F "eol=| delims=" %%I in (documentation.txt) do %SystemRoot%\System32\robocopy.exe "%~dp0." "E:\Destination" "%%~I" /S /NDL /NFL /NJH /NJS
It is assumed that the file documentation.txt contains a list of file names without path.
The command FOR reads one line after the other from file documentation.txt with skipping empty lines. The end of line character is modified from default ; to | using option eol=| to be able copying also files of which name starts unusually with a semicolon. No file name can contain a vertical bar anywhere. The line splitting behavior on spaces/tabs is disabled by using option delims= which defines in this case an empty list of string delimiters. Therefore file names with one or more space even at beginning of file name read from file are assigned unmodified to loop variable I. The option tokens=* removes leading spaces/tabs from the lines read from text file. A file name can begin with one or more spaces although such file names are unusual.
FOR runs for each file name the executable ROBOCOPY with directory of the batch file as source folder path and E:\Destination as destination folder path. ROBOCOPY interprets a \ left of one more \ or " as escape character. For that reason the source and destination folder paths should never end with a backslash as this would result in " being interpreted not as end of folder path, but everything up to next " in command line. For that reason . is appended to %~dp0 because of %~dp0 always expands to batch file folder path ending with a backslash. The dot at end of batch file folder path references the current folder of batch file folder. In other words with batch file stored in C:\Temp the batch file folder can be referenced with C:\Temp\ as done with %~dp0 but not possible with ROBOCOPY or with C:\Temp\. as done with %~dp0. or with just C:\Temp or with C:\Temp\\ as done with %~dp0\ which would also work with ROBOCOPY. See the Microsoft documentation about Naming Files, Paths, and Namespaces for details.
Remove %~dp0 to use current folder as source folder instead of batch file folder.
The ROBOCOPY option /S results in searching in source folder and all its subfolders for the file and copy each found file to destination folder with duplicating the source folder structure in destination folder.
The other ROBOCOPY options are just for not printing list of created directories, list of copied files, header and summary.
Here is an alternative command line for this task copying all files from source directory tree into destination directory without creating subdirectories. So all copied files are finally in specified destination directory.
for /F "eol=| delims=" %%I in (documentation.txt) do for /F "delims=" %%J in ('dir "%~dp0%%~I" /A-D-H /B /S 2^>nul') do copy /B /Y "%%J" "E:\Destination\" >nul
The inner FOR starts for each file name assigned to loop variable I of outer FOR one more command process in background with %ComSpec% /c and the DIR command line appended as additional arguments. So executed is for each file name in documentation.txt with Windows installed into C:\Windows for example:
C:\Windows\System32\cmd.exe /c dir "C:\Batch File Path\Current File Name.ext" /A-D-H /B /S 2>nul
The command DIR executed by second cmd.exe in background searches
in directory of the batch file
and all its subdirectories because of option /S
only for non-hidden files because of option /A-D-H (attribute not directory and not hidden)
with the specified file name
and outputs in bare format because of option /B
just the names of the found files with full path because of option /S.
It is possible that DIR cannot find a file matching these criteria at all in which case it would output an error message to handle STDERR of the background command process. This error message is suppressed by redirecting it with 2>nul to device NUL.
Read the Microsoft article about Using command redirection operators for an explanation of 2>nul. The redirection operator > must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded dir command line with using a separate command process started in background.
The inner FOR captures everything written to handle STDOUT of started background command process and processes this output line by line after started cmd.exe terminated itself after finishing execution of DIR.
The inner FOR assigns each full qualified file name to specified loop variable J without any modification because of option delims= and runs next the command COPY to copy that file as binary file to destination directory with automatically overwriting an existing file in destination directory with same file name. The success message output by COPY to handle STDOUT is redirected with >nul to device NUL to suppress it. An error message would be output by COPY. An error occurs if destination directory does not exist, or the destination directory is write-protected, or an existing file with same name is write-protected due to a read-only attribute or file permissions, or source file is opened by an application with sharing read access denied, or an existing destination file is opened by an application with sharing write access denied.
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.
call /? ... for an explanation of %~dp0 referencing drive and path of argument 0 which is the full qualified path of the batch file currently processed by cmd.exe.
copy /?
dir /?
for /?
robocopy /?

Run command on multiple subfolders on cmd

I have a lot of courses in subfolders that I have downloaded under (C:\Users\[username]\AppData\Local\lynda.com\Lynda.com Desktop App\offline\ldc_dl_courses) and I want to run this command on all subfolders under ldc_dl_courses but I have some problems creating a batch file to run it.
LyndaDecryptor /D “C:\Users\[username]\AppData\Local\lynda.com\Lynda.com Desktop App\offline\ldc_dl_courses\143455” /DB “C:\Users\[username]\AppData\Local\lynda.com\Lynda.com Desktop App\db.sqlite” /OUT “C:\Users\[username]\AppData\Local\lynda.com\Lynda.com Desktop App\offline\ldc_dl_courses\mp4”
I tried this but it didn't work
FOR /D %G IN ("C:\Users\salah\AppData\Local\lynda.com\Lynda.com Desktop App\offline\ldc_dl_courses") DO LyndaDecryptor /D "C:\Users\salah\AppData\Local\lynda.com\Lynda.com Desktop App\offline\ldc_dl_courses\%G" /DB "C:\Users\salah\AppData\Local\lynda.com\Lynda.com Desktop App\db.sqlite" /OUT "C:\Users\salah\AppData\Local\lynda.com\Lynda.com Desktop App\offline\ldc_dl_courses\mp4"
I suggest using following batch file for this task:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "LyndaAppFolder=%LocalAppData%\lynda.com\Lynda.com Desktop App"
set "CoursesFolder=%LyndaAppFolder%\offline\ldc_dl_courses"
for /D %%I in ("%CoursesFolder%\*") do if /I not "%%I" == "%CoursesFolder%\mp4" LyndaDecryptor.exe /D "%%I" /DB "%LyndaAppFolder%\db.sqlite" /OUT "%CoursesFolder%\mp4"
endlocal
It is unclear for me if mp4 in courses folder is a folder or file. I suppose it is a folder which should be skipped on processing all non hidden subfolders in courses folder which is the reason for the additional case-insensitive IF condition.
The command FOR searches because of /D for non hidden directories in specified directory matching the wildcard pattern * and assigns the name of a found directory with full path without surrounding double quotes to loop variable I. The name of a found directory would be assigned to loop variable I without path if just * would be used in round brackets because of current directory is the directory containing the courses directories.
I suppose that LyndaDecryptor is an executable with file extension .exe and appended the file extension on last but one command line. Best would be to specify LyndaDecryptor with full path and with file extension as in this case Windows command interpreter has not to search for an executable or script with that file name on each iteration of the loop.
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 /?
set /?
setlocal /?
See also Wikipedia article about Windows Environment Variables for predefined environment variable LOCALAPPDATA used in the batch file using CamelCase notation for better readability as environment variables are not case-sensitive on Windows in comparison to FOR loop variables which are case-sensitive.
FOR /D %G IN ("C:\Users\[u]\AppData\Local\lynda.com\Lynda.com Desktop App\offline\ldc_dl_courses\*") DO LyndaDecryptor /D "%G" /DB "C:\Users\[u]\AppData\Local\lynda.com\Lynda.com Desktop App\db.sqlite" /OUT "C:\Users\[u]\AppData\Local\lynda.com\Lynda.com Desktop App\offline\mp4"
this is the following working solution

batch xcopy only files that are not present in destination

-TheGame/
- Game files/
-> file1.whatever
-> file2.whatever
-> file3.whatever
-> Launcher.exe
-TheGameModed/
- Game files/
-> file1.whatever (the moded file)
-> Launcher.exe (the moded launcher)
I made a mod on a game and i want to create an installer for people to play my game.
In order to preventing backup problems (if the player want to revert to vanilla) i will put the mod folder aside the game folder.
The mod folder contain only the "moded files" and in want to make a batch that will copy file from the game folder that are not already present in the destination (even if there are not the same)
Is this right :
xcopy "../TheGame" "../TheGameModed" /q /s /e
There is a documentation here but i didn't find what i'm looking for :
https://www.computerhope.com/xcopyhlp.htm
I found only this :
/U Copies only files that already exist in destination.
But i need the opposite (Copies only files that doesn't exist in destination)
P.S. : When the batch copy files, it ask me if i want to overwrite or not, and since i have only few filesit is not so hard to type n few times. But the mod will be deleted if someone type y (that would be bad) and maybe next mod will contain more files :[
Perhaps ROBOCOPY can't be used because the game updating batch file should work also on Windows XP. In this case the following batch file could be perhaps used working on Windows NT4 and all later Windows versions:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
pushd "%~dp0"
for /F "delims=" %%I in ('dir "TheGame\*" /A-D /B /S 2^>nul') do call :CopyFile "%%I"
popd
endlocal
exit
:CopyFile
set "SourcePath=%~dp1"
set "TargetPath=%SourcePath:\TheGame\=\TheGameModed\%"
if not exist "%TargetPath%%~nx1" %SystemRoot%\System32\xcopy.exe "%~1" "%TargetPath%" /C /I /Q >nul
goto :EOF
The batch file first creates a local environment.
Next it pushes path of current directory on stack and sets the directory of the batch file as current directory. It is expected by this batch file being stored in the directory containing the subdirectories TheGame and TheGameModed.
Then command DIR is executed to output
the names of just all files because of /A-D (attribute not directory)
with name of file only because of /B (bare format)
in specified directory TheGame and all subdirectories because of /S
and with full path also because of /S.
This DIR command line is executed in a separate command process started by FOR in background with cmd.exe /C which captures everything written by this command process respectively by DIR to handle STDOUT.
Read the Microsoft article about Using Command Redirection Operators for an explanation of 2>nul. The redirection operator > must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes DIR command line with using a separate command process started in background.
The FOR option delims= disables the standard behavior of splitting up each non empty line not starting with a semicolon into strings using space/tab as delimiter. In other words each file name with file extension and full path is assigned to loop variable I.
The name of each file with file extension and full path is passed to a subroutine called CopyFile.
The subroutine first assigns just path of source file found in TheGame directory tree to environment variable SourcePath. Next a string substitution is used to replace in this path TheGame by TheGameModed with including the directory separators on both side for more accuracy.
After having target path for current file in TheGame directory tree it is checked next if a file with that name in that path exists already in TheGameModed directory tree.
If the file does not exist, command XCOPY is used to copy this single file to TheGameModed with automatically creating the entire directory tree if that is necessary. This directory creation feature of XCOPY is the main reason for using XCOPY instead of COPY.
After processing all files in TheGame directory tree, the initial current directory is restored from stack as well as the initial environment before exiting current command process independent on calling hierarchy and how the command process was started initially.
The commands POPD and ENDLOCAL would not be really necessary with exit being the next line. I recommend usually to use exit /B or goto :EOF instead of EXIT, but goto :EOF fails if command extensions are not enabled and we can't be 100% sure that the command extensions are enabled on starting the batch file although by default command extensions are enabled on Windows.
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.
call /?
echo /?
endlocal /?
exit /?
goto /?
if /?
popd /?
pushd /?
set /?
setlocal /?
xcopy /?

How to move files from specific subdirectories to a subdirectory in base directory of a directory tree?

The base directory has about 20 subdirectories. Each subdirectory has many files. I need to move all the files from specific subdirectories to a newly created subdirectory in base directory at once.
For example I have in base directory D:\Documents the following directories:
D:\Documents\12345\data\images\
D:\Documents\12345\test\
D:\Documents\12345\documents\
I need to move all the files under images into newly to create directory D:\Documents\images in base directory.
Can you please help me in this?
This small batch file makes the job:
#echo off
md D:\Documents\images 2>nul
for /F "delims=" %%I in ('dir D:\Documents\* /A-D /B /S 2^>nul ^| %SystemRoot%\System32\findstr.exe /B /I /R /C:D:\\Documents\\..*\\images\\ 2^>nul') do (
move /Y "%%I" "D:\Documents\images\%%~nxI"
rd "%%~dpI" 2>nul
)
The batch file first creates the target directory with suppressing the error message output by MD if this directory already exists. It is expected by this batch file that it is possible to create this directory and move the files into this directory without any additional checks.
Command DIR searches in D:\Documents and all it subdirectories because of /S for just files because of /A-D (attribute not directory) and outputs them in bare format because of /B which means just the file name with file extension and in this case also with full path because of /S.
It is possible that DIR cannot find any file in entire D:\Documents directory tree. The error message output in this case to handle STDERR is suppressed by redirecting it to device NUL using 2>nul after command DIR.
This output by DIR is redirected as input for command FINDSTR used as filter. It runs a regular expression find searching for lines starting with D:\Documents\ having at least one more character before \images\ must be found too. So it ignores the files in directory D:\Documents\images\ in case of this directory already exists with files on starting the batch file. But it does not filter out files in for example D:\Documents\12345\data\images\Subfolder\ as this regular expression does not check if \images\ is found at end of path.
It is possible that FINDSTR does not find any line (file name) matching the regular expression. The error message output in this case is suppressed by using 2>nul after command FINDSTR.
The command line with DIR and FINDSTR is executed by FOR in a separate command process started with cmd.exe /C in background without a visible window. For that reason the redirection operators > and | must be escaped with ^ to be interpreted first as literal characters by the Windows command interpreter on parsing the entire FOR command line before execution of FOR.
The lines output by the command line with DIR and FINDSTR to handle STDOUT in separate command process is captured by FOR and then processed line by line. With delims= the default behavior of splitting each line up into tokens using space and horizontal tab as delimiters is disabled by specifying an empty delimiters list.
The command MOVE moves the found file to D:\Documents\images\ with overwriting a file with same name in that directory.
The command RD removes the directory of just moved file if this directory is empty now after moving the file. Otherwise on directory not yet being empty an error message is output by command RD to handle STDERR which is suppressed using once again 2>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.
dir /?
echo /?
findstr /?
for /?
md /?
move /?
rd /?
Read also the Microsoft article about Using Command Redirection Operators.

How to delete files/subfolders in a specific directory at the command prompt in Windows

Say, there is a variable called %pathtofolder%, as it makes it clear it is a full path of a folder.
I want to delete every single file and subfolder in this directory, but not the directory itself.
But, there might be an error like 'this file/folder is already in use'... when that happens, it should just continue and skip that file/folder.
Is there some command for this?
rmdir is my all time favorite command for the job. It works for deleting huge files and folders with subfolders. A backup is not created, so make sure that you have copied your files safely before running this command.
RMDIR "FOLDERNAME" /S /Q
This silently removes the folder and all files and subfolders.
You can use this shell script to clean up the folder and files within C:\Temp source:
del /q "C:\Temp\*"
FOR /D %%p IN ("C:\Temp\*.*") DO rmdir "%%p" /s /q
Create a batch file (say, delete.bat) containing the above command. Go to the location where the delete.bat file is located and then run the command: delete.bat
The simplest solution I can think of is removing the whole directory with
RD /S /Q folderPath
Then creating this directory again:
MD folderPath
This will remove the folders and files and leave the folder behind.
pushd "%pathtofolder%" && (rd /s /q "%pathtofolder%" 2>nul & popd)
#ECHO OFF
SET THEDIR=path-to-folder
Echo Deleting all files from %THEDIR%
DEL "%THEDIR%\*" /F /Q /A
Echo Deleting all folders from %THEDIR%
FOR /F "eol=| delims=" %%I in ('dir "%THEDIR%\*" /AD /B 2^>nul') do rd /Q /S "%THEDIR%\%%I"
#ECHO Folder deleted.
EXIT
...deletes all files and folders underneath the given directory, but not the directory itself.
CD [Your_Folder]
RMDIR /S /Q .
You'll get an error message, tells you that the RMDIR command can't access the current folder, thus it can't delete it.
Update:
From this useful comment (thanks to Moritz Both), you may add && between, so RMDIR won't run if the CD command fails (e.g. mistyped directory name):
CD [Your_Folder] && RMDIR /S /Q .
From Windows Command-Line Reference:
/S: Deletes a directory tree (the specified directory and all its
subdirectories, including all files).
/Q: Specifies quiet mode. Does not prompt for confirmation when
deleting a directory tree. (Note that /q works only if /s is
specified.)
I use Powershell
Remove-Item c:\scripts\* -recurse
It will remove the contents of the folder, not the folder itself.
RD stands for REMOVE Directory.
/S : Delete all files and subfolders
in addition to the folder itself.
Use this to remove an entire folder tree.
/Q : Quiet - do not display YN confirmation
Example :
RD /S /Q C:/folder_path/here
Use Notepad to create a text document and copy/paste this:
rmdir /s/q "%temp%"
mkdir "%temp%"
Select Save As and file name:
delete_temp.bat
Save as type: All files and click the Save button.
It works on any kind of account (administrator or a standard user). Just run it!
I use a temporary variable in this example, but you can use any other! PS: For Windows OS only!
None of the answers as posted on 2018-06-01, with the exception of the single command line posted by foxidrive, really deletes all files and all folders/directories in %PathToFolder%. That's the reason for posting one more answer with a very simple single command line to delete all files and subfolders of a folder as well as a batch file with a more complex solution explaining why all other answers as posted on 2018-06-01 using DEL and FOR with RD failed to clean up a folder completely.
The simple single command line solution which of course can be also used in a batch file:
pushd "%PathToFolder%" 2>nul && ( rd /Q /S "%PathToFolder%" 2>nul & popd )
This command line contains three commands executed one after the other.
The first command PUSHD pushes current directory path on stack and next makes %PathToFolder% the current directory for running command process.
This works also for UNC paths by default because of command extensions are enabled by default and in this case PUSHD creates a temporary drive letter that points to that specified network resource and then changes the current drive and directory, using the newly defined drive letter.
PUSHD outputs following error message to handle STDERR if the specified directory does not exist at all:
The system cannot find the path specified.
This error message is suppressed by redirecting it with 2>nul to device NUL.
The next command RD is executed only if changing current directory for current command process to specified directory was successful, i.e. the specified directory exists at all.
The command RD with the options /Q and /S removes a directory quietly with all subdirectories even if the specified directory contains files or folders with hidden attribute or with read-only attribute set. The system attribute does never prevent deletion of a file or folder.
Not deleted are:
Folders used as the current directory for any running process. The entire folder tree to such a folder cannot be deleted if a folder is used as the current directory for any running process.
Files currently opened by any running process with file access permissions set on file open to prevent deletion of the file while opened by the running application/process. Such an opened file prevents also the deletion of entire folder tree to the opened file.
Files/folders on which the current user has not the required (NTFS) permissions to delete the file/folder which prevents also the deletion of the folder tree to this file/folder.
The first reason for not deleting a folder is used by this command line to delete all files and subfolders of the specified folder, but not the folder itself. The folder is made temporarily the current directory for running command process which prevents the deletion of the folder itself. Of course this results in output of an error message by command RD:
The process cannot access the file because it is being used by another process.
File is the wrong term here as in reality the folder is being used by another process, the current command process which executed command RD. Well, in reality a folder is for the file system a special file with file attribute directory which explains this error message. But I don't want to go too deep into file system management.
This error message, like all other error messages, which could occur because of the three reasons written above, is suppressed by redirecting it with 2>nul from handle STDERR to device NUL.
The third command, POPD, is executed independently of the exit value of command RD.
POPD pops the directory path pushed by PUSHD from the stack and changes the current directory for running the command process to this directory, i.e. restores the initial current directory. POPD deletes the temporary drive letter created by PUSHD in case of a UNC folder path.
Note: POPD can silently fail to restore the initial current directory in case of the initial current directory was a subdirectory of the directory to clean which does not exist anymore. In this special case %PathToFolder% remains the current directory. So it is advisable to run the command line above not from a subdirectory of %PathToFolder%.
One more interesting fact:
I tried the command line also using a UNC path by sharing local directory C:\Temp with share name Temp and using UNC path \\%COMPUTERNAME%\Temp\CleanTest assigned to environment variable PathToFolder on Windows 7. If the current directory on running the command line is a subdirectory of a shared local folder accessed using UNC path, i.e. C:\Temp\CleanTest\Subfolder1, Subfolder1 is deleted by RD, and next POPD fails silently in making C:\Temp\CleanTest\Subfolder1 again the current directory resulting in Z:\CleanTest remaining as the current directory for the running command process. So in this very, very special case the temporary drive letter remains until the current directory is changed for example with cd /D %SystemRoot% to a local directory really existing. Unfortunately POPD does not exit with a value greater 0 if it fails to restore the initial current directory making it impossible to detect this very special error condition using just the exit code of POPD. However, it can be supposed that nobody ever runs into this very special error case as UNC paths are usually not used for accessing local files and folders.
For understanding the used commands even better, open a command prompt window, execute there the following commands, and read the help displayed for each command very carefully.
pushd /?
popd /?
rd /?
Single line with multiple commands using Windows batch file explains the operators && and & used here.
Next let us look on the batch file solution using the command DEL to delete files in %PathToFolder% and FOR and RD to delete the subfolders in %PathToFolder%.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem Clean the folder for temporary files if environment variable
rem PathToFolder is not defined already outside this batch file.
if not defined PathToFolder set "PathToFolder=%TEMP%"
rem Remove all double quotes from folder path.
set "PathToFolder=%PathToFolder:"=%"
rem Did the folder path consist only of double quotes?
if not defined PathToFolder goto EndCleanFolder
rem Remove a backslash at end of folder path.
if "%PathToFolder:~-1%" == "\" set "PathToFolder=%PathToFolder:~0,-1%"
rem Did the folder path consist only of a backslash (with one or more double quotes)?
if not defined PathToFolder goto EndCleanFolder
rem Delete all files in specified folder including files with hidden
rem or read-only attribute set, except the files currently opened by
rem a running process which prevents deletion of the file while being
rem opened by the application, or on which the current user has not
rem the required permissions to delete the file.
del /A /F /Q "%PathToFolder%\*" >nul 2>nul
rem Delete all subfolders in specified folder including those with hidden
rem attribute set recursive with all files and subfolders, except folders
rem being the current directory of any running process which prevents the
rem deletion of the folder and all folders above, folders containing a file
rem opened by the application which prevents deletion of the file and the
rem entire folder structure to this file, or on which the current user has
rem not the required permissions to delete a folder or file in folder tree
rem to delete.
for /F "eol=| delims=" %%I in ('dir "%PathToFolder%\*" /AD /B 2^>nul') do rd /Q /S "%PathToFolder%\%%I" 2>nul
:EndCleanFolder
endlocal
The batch file first makes sure that environment variable PathToFolder is really defined with a folder path without double quotes and without a backslash at the end. The backslash at the end would not be a problem, but double quotes in a folder path could be problematic because of the value of PathToFolder is concatenated with other strings during batch file execution.
Important are the two lines:
del /A /F /Q "%PathToFolder%\*" >nul 2>nul
for /F "eol=| delims=" %%I in ('dir "%PathToFolder%\*" /AD /B 2^>nul') do rd /Q /S "%PathToFolder%\%%I" 2>nul
The command DEL is used to delete all files in the specified directory.
The option /A is necessary to process really all files including files with the hidden attribute which DEL would ignore without using option /A.
The option /F is necessary to force deletion of files with the read-only attribute set.
The option /Q is necessary to run a quiet deletion of multiple files without prompting the user if multiple files should be really deleted.
>nul is necessary to redirect the output of the file names written to handle STDOUT to device NUL of which can't be deleted because of a file is currently opened or user has no permission to delete the file.
2>nul is necessary to redirect the error message output for each file which can't be deleted from handle STDERR to device NUL.
The commands FOR and RD are used to remove all subdirectories in specified directory. But for /D is not used because of FOR is ignoring in this case subdirectories with the hidden attribute set. For that reason for /F is used to run the following command line in a separate command process started in the background with %ComSpec% /c:
dir "%PathToFolder%\*" /AD /B 2>nul
DIR outputs in bare format because of /B the directory entries with attribute D, i.e. the names of all subdirectories in specified directory independent on other attributes like the hidden attribute without a path. 2>nul is used to redirect the error message output by DIR on no directory found from handle STDERR to device NUL.
The redirection operator > must be escaped with the caret character, ^, on the FOR command line to be interpreted as a literal character when the Windows command interpreter processes this command line before executing the command FOR which executes the embedded dir command line in a separate command process started in the background.
FOR processes the captured output written to handle STDOUT of a started command process which are the names of the subdirectories without path and never enclosed in double quotes.
FOR with option /F ignores empty lines which don't occur here as DIR with option /B does not output empty lines.
FOR would also ignore lines starting with a semicolon which is the default end of line character. A directory name can start with a semicolon. For that reason eol=| is used to define the vertical bar character as the end-of-line character which no directory or file can have in its name.
FOR would split up the line into substrings using space and horizontal tab as delimiters and would assign only the first space/tab delimited string to specified loop variable I. This splitting behavior is not wanted here because of a directory name can contain one or more spaces. Therefore delims= is used to define an empty list of delimiters to disable the line splitting behavior and get assigned to the loop variable, I, always the complete directory name.
Command FOR runs the command RD for each directory name without a path which is the reason why on the RD command line the folder path must be specified once again which is concatenated with the subfolder name.
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.
del /?
dir /?
echo /?
endlocal /?
for /?
goto /?
if /?
rd /?
rem /?
set /?
setlocal /?
To delete file:
del PATH_TO_FILE
To delete folder with all files in it:
rmdir /s /q PATH_TO_FOLDER
To delete all files from specific folder (not deleting folder itself) is a little bit complicated. del /s *.* cannot delete folders, but removes files from all subfolder. So two commands are needed:
del /q PATH_TO_FOLDER\*.*
for /d %i in (PATH_TO_FOLDER\*.*) do #rmdir /s /q "%i"
You can do it by using the following command to delete all contents and the parent folder itself:
RMDIR [/S] [/Q] [drive:]path
#ECHO OFF
rem next line removes all files in temp folder
DEL /A /F /Q /S "%temp%\*.*"
rem next line cleans up the folder's content
FOR /D %%p IN ("%temp%\*.*") DO RD "%%p" /S /Q
I tried several of these approaches, but none worked properly.
I found this two-step approach on the site Windows Command Line:
forfiles /P %pathtofolder% /M * /C "cmd /c if #isdir==FALSE del #file"
forfiles /P %pathtofolder% /M * /C "cmd /c if #isdir==TRUE rmdir /S /Q #file"
It worked exactly as I needed and as specified by the OP.
I had following solution that worked for me:
for /R /D %A in (*node_modules*) do rmdir "%A" /S /Q
It removes all node modules folder from current directory and its sub-folders.
This is similar to solutions posted above, but i am still posting this here, just in case someone finds it useful
Use:
del %pathtofolder%\*.* /s /f /q
This deletes all files and subfolders in %pathtofolder%, including read-only files, and does not prompt for confirmation.

Resources