CMD to delete a specific folder with files from multiple folder paths - batch-file

I need a CMD batch file to delete all the log files.
My company makes plugins for their product and the path is something as follows:
C:/Program Files/product/../plugins/../plugin_Path/pluginOne/audit/log
C:/Program Files/product/../plugins/../plugin_Path/pluginOne/audit/log-archive
C:/Program Files/product/../Root/plugins/../plugin_Path/pluginTwo/audit/log
C:/Program Files/product/../Root/plugins/../plugin_Path/pluginTwo/audit/log-archive
Now I need to delete all the log and log-archive folders with its contains.
Currently I wrote a samll program like this:
#echo off
color 02
for %%A in (
"C:/Program Files/product/plugins/plugin_Path/pluginOne/audit/log"
"C:/Program Files/product/plugins/plugin_Path/pluginOne/audit/log-archive"
"C:/Program Files/product/plugins/plugin_Path/pluginTwo/audit/log"
"C:/Program Files/product/plugins/plugin_Path/pluginTwo/audit/log-archive"
) do (
del /Q %%A
echo Deleted %%A
)
echo All files deleted
pause
echo Program ended
But here I need to insert all the log paths manually.
I am looking for a solution where I could point the parent folder (say Program Files/Company) and it could traverse all the files inside and will delete all the log and log-archival folders with its contains.
I am a QA person have good QA experience but no experience on batch programming and I dont have much time and support team is not present. [Need help]. There are more than 1K log files are present.

First, as explained by the Microsoft documentation Naming Files, Paths, and Namespaces, the directory separator on Windows is \ and not / as on Linux/Mac. / is used on Windows for options as you can see on your code for example on /Q. So use in future \ in file/folder paths. The Windows file system accessing kernel functions automatically replace all forward slashes by backslashes before accessing the file systems, but writing code depending on automatic error correction is never a good idea.
The task to delete all folders with name log or log-archive in a specified folder and all its subfolders can be done with a single command line.
#for /F "delims=" %%I in ('dir "%ProgramFiles%\product\plugins\plugin_Path\log*" /AD /B /S 2^>nul ^| %SystemRoot%\System32\findstr.exe /E /I /R "\\log \\log-archive"') do #rd /Q /S "%%I" 2>nul
FOR with option /F runs in a separate command process started with cmd.exe /C (more precise with %ComSpec% /C) in background the command line in '... ' which is here:
dir "C:\Program Files\product\plugins\plugin_Path\log*" /AD /B /S 2>nul | C:\Windows\System32\findstr.exe /E /I /R "\\log \\log-archive"
The command DIR outputs to handle STDOUT
in bare format because of option /B
just directories because of option /AD (attribute directory)
directory names matching the wildcard pattern log*
in specified directory C:\Program Files\product\plugins\plugin_Path
and all its subdirectories because of option /S
with full path also because of option /S.
It could be that DIR does not find any file system entry matching these criteria. In this case an error message is output by DIR to handle STDERR. This error output is redirected with 2>nul to device NUL to suppress it.
The standard output of DIR is redirected with | to handle STDIN of FINDSTR which runs
because of option /I a case-insensitive
regular expression find explicitly requested with option /R
for string \log or \log-archive (space is interpreted as OR)
which must be found at end of a line because of option /E.
All lines matching these search criteria are output by FINDSTR to handle STDOUT of background command process. This filtering of output of DIR with FINDSTR is necessary to avoid the deletion of a directory which is named for example LogToKeep also found and output by DIR.
Read the Microsoft article about Using Command Redirection Operators for an explanation of 2>nul and |. The redirection operators > and | must be escaped with caret character ^ on FOR command line to be interpreted as literal characters when Windows command interpreter processes this command line before executing command FOR which executes the embedded command line with using a separate command process started in background.
FOR with option /F captures output to handle STDOUT of started command process and processes this output line by line after started cmd.exe terminated itself. Empty lines are always ignored by FOR which do not occur here. Lines starting with a semicolon are also ignored by default because of eol=; is the default definition for end of line option. But a full qualified folder path cannot contain a semicolon at beginning because the folder path starts either with a drive letter or with a backslash in case of a UNC path. So default end of line option can be kept in this case. FOR would split up by default every line into substrings with using normal space and horizontal tab as string delimiters and would assign just first space/tab separated string to specified loop variable. This line splitting behavior is not wanted here as the folder path contains definitely a space character and the entire folder path is needed and not just the string up to first space. For that reason delims= is used to specify an empty list of delimiters which disables line splitting behavior.
FOR executes for every directory output by DIR passing FINDSTR filter with full path the command RD to remove the directory quietly because of option /Q and with all files and subdirectories because of /S.
The deletion of the directory could fail because of missing NTFS permissions, or the directory to delete or one of its subdirectories is current directory of a running process, or a file in the directory to delete is currently opened by a running process in a manner which denies deletion of the file while being opened, or the directory to delete does not exist anymore because it was deleted already before in FOR loop. The error message output by command RD to handle STDERR is in this case redirected to device NUL to suppress it.
Please note that command RD deletes all log and log-archives directories and not just the files and subdirectories in these directories. It is unclear from your question what exactly should be deleted by the batch file.
It is of course also possible to replace rd /Q /S "%%I" by del /A /F /Q "%%I\*" to delete just all files including hidden and read-only files quietly in the directory assigned with full path to loop variable I.
# left to command FOR and command RD just suppress the output of those commands before execution by Windows command processor cmd.exe. Both # are not needed if this single command line is used in a batch file containing before #echo off.
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 /?
findstr /?
for /?
rd /?

If you're wanting to remove the contents of the log and log-archive directories. This means the easiest solution would probably be FORFILES.
This will delete all the files under log and log-archive directories found within any subfolder of "C:\Program Files\product\plugins". The folders MUST be named exactly log or log-archive. It will not remove directories.
FORFILES /P "C:\Program Files\product\plugins" /M log /C "cmd /c if #isdir==TRUE DEL /s /q #path\*"
FORFILES /P "C:\Program Files\product\plugins" /M log-archive /C "cmd /c if #isdir==TRUE DEL /s /q #path\*"
You could also add a /D switch to only delete applicable files if they are older than a specific number of days. This will delete all the log and log-archive files under "C:\Program Files\product\plugins" that are older than 90 days:
FORFILES /D -90 /P "C:\Program Files\product\plugins" /M log /C "cmd /c if #isdir==TRUE DEL /s /q #path\*"
FORFILES /D -90 /P "C:\Program Files\product\plugins" /M log-archive /C "cmd /c if #isdir==TRUE DEL /s /q #path\*"

Related

how to zip all files individually in all subfolders and remove original file after

what im looking for is a .bat file code to zip files individually in all subfolders in the current folder and then delete the of files after, to exclude already zipped/compressed files, what i dont want is folders to be zipped and i want the files to keep there name when zipped
i have a bunch of folders/files and the only code i found
#ECHO OFF
FOR %%i IN (*.*) DO (
ECHO "%%i" | FIND /I "batch zip files.bat" 1>NUL) || (
"c:\Program Files\7-Zip\7z.exe" a -tzip "%%~ni.zip" "%%i"
if %ERRORLEVEL% == 0 del "%%i"
)
)
zips all files in the current directory and doesnt touch subfolders
i'd appreciate it if anyone can do this for me as i can save a ton of space with all files zipped
The first issue you have with your provided code is that your For loop is only parsing files in the current directory, there is no recursion into subdirectories. To parse files within the subdirectories, I'd advise that you use a For /F loop, with the Dir command using its /B and /S options. I would also advise that you include the attribute option, /A, which will include every item, then omit those which you're not interested in. For instance, it's unlikely that you want to zip the directories, hidden files, reparse points, or system files. You can do that by excluding those attributes, /A:-D-H-L-S. To learn more about the For command, and the Dir command, open a Command Prompt window, type for /?, and press the ENTER key. You can then do the same for the Dir command, i.e for /?. As you have not defined a working directory at the start of your script, it will run against every file and directory in whatever is current at the time you run it. Because your code has a line excluding a file named batch zip files.bat, I'm going to assume that is the name of your running script, and that your intention is to therefore run the script against everything in the tree rooted from the same location as the batch file itself. To ensure that is always the case, for safety, I've defined that directory as the current directory from the outset, using the CD command, CD /D "%~dp0". %0 is a special batch file argument reference to itself, to learn more about this please take a look at the output from both call /?. You can also learn about the CD command entering cd /?, in a Command Prompt window too. To also omit your batch file, as you don't want it to be zipped and deleted, I've piped the results from the Dir command through FindStr, printing only items which do not exactly match the case insensitive literal string %~f0 (expanding to the full path of the batch file itself). Additionally, I've piped those results through another findstr.exe command to omit any files already carrying a .zip extension, as there's no point in zipping files which already zip files. (Please note however, that for more robust code, you should really check that those are zip archives and not just files carrying a misleading extension). The results from those commands are then passed one by one to the Do portion which includes your 7z.exe command. I've assumed at this stage, that your intention was to save the zipped archives to the same location as the originating files. To do that I've used variable expansion on %%G to stipulate its directory, path, and name, %%~dpnG, (see the usage information under for /? to recap). Upon successful completion of the archiving process, the original file will be deleted, to do that I appended the -sdel option to your original command string. Please be aware that you may want to include additional options, should you wish to update existing zip files etc. (use "%ProgramFiles%\7-Zip\7z.exe" -? in a Command Prompt window to see them). As I've not mentioned it previously, at the beginning of the script, I made sure that extensions were enabled. Whilst it is the default option, it's safer to be sure, as variable expansion and the commands CD, and For can be affected, if they're not.
Here's the code as explained above:
#Echo Off
SetLocal EnableExtensions
CD /D "%~dp0"
For /F "EOL=? Delims=" %%G In ('Dir "*" /A:-D-H-L-S /B /S 2^> NUL ^|
%SystemRoot%\System32\findstr.exe /I /L /V /X "%~f0" ^|
%SystemRoot%\System32\findstr.exe /E /I /L /V ".zip"'
) Do "%ProgramFiles%\7-Zip\7z.exe" a -tzip "%%~dpnG.zip" "%%G" -sdel
Looking at your question, which has changed from what you'd asked initially, you appear to not be interested in the files of the batch file directory any more, "zip files individually in all subfolders in the current folder". For that reason, I've provided the following alternative, methodology.
The difference is that I first of all use a For loop to include only directories in the current working location, /A:D-H-L-S, before running the same method used in my previous example, but with one difference. As we're now no longer zipping files in the current working directory, we can remove the findstr.exe command filtering out the running batch file:
#Echo Off
SetLocal EnableExtensions
CD /D "%~dp0"
For /F "EOL=? Delims=" %%G In ('Dir "*" /A:D-H-L-S /B 2^> NUL'
) Do For /F "EOL=? Delims=" %%H In ('Dir "%%G" /A:-D-H-L-S /B /S 2^> NUL ^|
%SystemRoot%\System32\findstr.exe /E /I /L /V ".zip"'
) Do "%ProgramFiles%\7-Zip\7z.exe" a -tzip "%%~dpnH.zip" "%%H" -sdel
Please be aware, that my answers above are to essentially correct your code attempt, and not a personal recommendation for speed, or in performing the task laid out in your question. Additionally, I have no idea what will happen if any of those files are in use/locked, and have made no attempt at checking for such scenarios.

Find Specific *.exe files in directories and run the app with parameters

I'm trying to find recursively all "MyApp.exe" apps in "C:\Builds" folder and run the apps with "createdatabase closeimmediately" arguments/parameters.
What I search so far:ForFiles Microsoft docs
Here is the forfiles pattern:
forfiles [/p <Path>] [/m <SearchMask>] [/s] [/c "<Command>"] [/d [{+|-}][{|}]]
Here is what I have:
forfiles /p c:\Builds /s /m MyApp.exe /c "cmd /c start #path" "createdatabase closeimmediately"
If I run above script, it is showing error:
ERROR: Invalid argument/option - 'createdatabase closeimmediately'.Type "FORFILES /?" for usage.
If I run without parameteres, it finds apps correctly and runs, but I need to run with parameters:
forfiles /p c:\Builds /s /m MyApp.exe /c "cmd /c start #path"
How can I run apps with parameters in ForFiles?
I know this was mentioned in the comments, but the comments are becoming too long for me to post a decent comment still, so here is an answer. This should do exactly what you want, it will recursively search for the file and execute if exists.
#echo off
for /r "c:\Builds" %%i in (myapp.exe) do if exist "%%i" "%%i" createdatabase closeimmediately
a slightly different way, find all executables, and launch if the name matches myapp.exe:
for /r "c:\Builds" %%i in (*.exe) do if /I "%%~nxi" == "myapp.exe" "%%I" createdatabase closeimmediately
There are multiple methods possible to search for MyApp.exe in C:\Build and all subfolders and execute the found executable with the two parameters createdatabase and closeimmediately.
The first solution uses command FOR to search for any file matching the wildcard pattern MyApp*.exe in C:\Build and any non-hidden subfolder.
For usage in a batch file:
for /R "C:\Build" %%I in ("MyApp*.exe") do if /I "%%~nxI" == "MyApp.exe" "%%I" createdatabase closeimmediately
For usage in command prompt window:
for /R "C:\Build" %I in ("MyApp*.exe") do #if /I "%~nxI" == "MyApp.exe" "%I" createdatabase closeimmediately
It is necessary that the string inside the round brackets contains at least one * or ? to define a wildcard pattern. Otherwise FOR would not search for files with name MyApp.exe on using just "MyApp.exe" in C:\Build and all its subfolders. It would simply append the string "MyApp.exe" (with the double quotes) to folder path of every folder found in C:\Build folder structure and would assign folder path + "MyApp.exe" to loop variable I and execute the command line referencing the loop variable.
The IF condition is used to make sure that only MyApp.exe is executed and not for example MyAppOther.exe found by chance also by FOR with wildcard pattern MyApp*.exe. The string comparison is done case-insensitive because of /I.
It would be also possible to use a different wildcard pattern like MyApp.exe*. This could reduce the number of false positives. But for security the IF condition should be nevertheless used.
The second solution is using just MyApp.exe and check if a file with that name really exists in the given folder path before executing it.
For usage in a batch file:
for /R "C:\Build" %%I in (MyApp.exe) do if exist "%%I" "%%I" createdatabase closeimmediately
For usage in command prompt window:
for /R "C:\Build" %I in (MyApp.exe) do #if exist "%I" "%I" createdatabase closeimmediately
MyApp.exe is specified in round brackets without being enclosed in " as otherwise the string assigned to loop variable I would be for example C:\Build\"MyApp.exe" and not C:\Build\MyApp.exe. By automatic error correction the string value C:\Build\"MyApp.exe" might also work depending on which string is really used instead of MyApp.exe. But this is not really a safe method and does not work if the string MyApp.exe contains a space, comma, semicolon, or other characters like &()[]{}^=;!'+,`~.
The third solution is using the command DIR for searching for MyApp.exe without a wildcard pattern to find only files with exactly that name and let FOR execute the found executables with that name.
For usage in a batch file:
for /F "delims=" %%I in ('dir "C:\Build\MyApp.exe" /A-D-H /B /S 2^>nul') do "%%I" createdatabase closeimmediately
For usage in command prompt window:
for /F "delims=" %I in ('dir "C:\Build\MyApp.exe" /A-D-H /B /S 2^>nul') do #"%I" createdatabase closeimmediately
In comparison to FOR the command DIR really searches for files with name MyApp.exe even on argument string not containing a wildcard character like * or ?.
FOR executes the DIR command line in a separate command process started with cmd.exe /C in background and captures everything written to handle STDOUT of this command process.
Read also 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.
2>nul is used to suppress the error message output by DIR to handle STDERR by redirecting it to device NUL if no file MyApp.exe could be found in C:\Build or its subdirectories.
DIR outputs because of /B and /S just the full qualified file name, i.e. file path + file name + file extension, of every found MyApp.exe line by line.
FOR processes the captured output line by line with skipping empty lines and lines starting with a semicolon. Such lines are surely not output by DIR with the used options.
FOR would also split up each line into substrings (tokens) on spaces/tabs and would assign only first substring to loop variable I. This string splitting behavior is not wanted here as a folder name could contain one or more spaces. For that reason FOR option delims= is used to define an empty list of delimiters which disables the line splitting behavior.
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 /?
for /?
if /?

Delete files in a folder but keep the last generated file

I need to delete files in an specific folder with a batch script, however, I need to keep the last file generated. Our server has an IIS folder that keeps generating logs, and we need to keep always the last one, but delete the older ones.
Currently we have this script that deletes all the files in an specific folder (in this case, all the files inside C:\Temp):
del /q "C:\Temp\*"
FOR /D %%p IN ("C:\Temp\*.*") DO rmdir "%%p" /s /q
How could we edit that code to keep the last file generated in the folder?
Thank you in advance for your help.
This batch file offers one solution:
#echo off
set "SourceFolder=C:\Temp"
for /F "skip=1 delims=" %%I in ('dir "%SourceFolder%\*" /A-D /B /O-D 2^>nul') do del "%SourceFolder%\%%I"
set "SourceFolder="
The command DIR outputs a list of just file names because of the options /A-D (directory entries with directory attribute not set) and /B (bare format) ordered reverse by last modification date because of /O-D which means the name of the newest modified file is output first.
An error message output by DIR if the specified folder does not contain any file is suppressed by redirecting the error message written to handle STDERR to device NUL using 2>nul. The redirection operator > must be escaped here with caret character ^ to be interpreted as literal character on processing the entire FOR command line by Windows command interpreter. Later FOR executes in a separate command process in background the command dir "%SourceFolder%\*" /A-D /B /O-D 2>nul and captures the output written to STDOUT.
FOR option skip=1 results in skipping first line of captured output which means ignoring the file name of newest modified file.
FOR option delims= disables the default splitting up of the captured lines into space/tab separated strings as every entire file name should be assigned to loop variable I for usage by command executed by FOR.
DEL deletes the file if that is possible at all.
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 /?
for /?
set /?
Read also the Microsoft article about Using Command Redirection Operators.

How to use a FOR loop to act on files which don't fulfil a condition?

I'm making a simple batch script to process a large set of files and delete all I don't want. I want about 10% of the files and they all have certain tags in their names, lets say they contain apple, orange or pear. As there are so many files I want deleted, it would be quite time consuming to construct a FOR loop such as:
#echo off
pause
for /R %%i in ([the list of names of the files I don't want]) do del %%i
pause
So I was wondering if it is possible to code it such that it deletes all files which don't have names containing apple, orange or pear?
In other words all files should be deleted not containing in its name one of those 3 words.
I'm using a FOR loop because the files are nested within lots of subdirectories and I would like to preserve this structure after the unwanted files have been deleted.
You can use this batch file containing (more or less) just one command line:
#echo off
for /F "delims=" %%I in ('dir * /A-D /B /S 2^>nul ^| %SystemRoot%\System32\findstr.exe /I /R /V /C:"apple[^\\]*$" /C:"orange[^\\]*$" /C:"pear[^\\]*$"') do ECHO del "%%I"
This batch code does not really delete files because of command ECHO before del at end of the command line. Run this batch file from within a command prompt window with current directory being the root of the directory tree on which to delete unwanted files and verify the output. Then remove ECHO and run the batch file once again.
The command DIR searches because of /S in current directory and all subdirectories only for files because of /A-D (not directory attribute) matching the wildcard pattern * with output in bare format because of /B which means the output contains just the names of all found files with full path.
DIR outputs an error message to handle STDERR if it can't find any file. This error message is suppressed by redirecting it to device NUL with 2>nul. The redirection operator > must be escaped here with caret character ^ to be first interpreted as literal character on parsing the FOR command line by Windows command interpreter.
The output of DIR to handle STDOUT is piped with | to standard console application FINDSTR which searches in all lines case-insensitive because of /I for the regular expression strings because of /R specified with /C:. The redirection operator | must be escaped here also with ^.
An OR expression is not supported by FINDSTR like it is by other applications with regular expression support. But it is possible to specify multiple search strings as done here which are all applied on each line of the text to process one after the other until a positive match occurs or there is no more search string. That is a classic OR.
The regular expression word[^\\]*$ means:
word ... There must be found word (case-insensitive).
[^\\]* ... Find 0 or more characters NOT being a backslash.
$ ... The matching string must be found at end of line.
The regular expression is used to get a positive match only for lines on which the file name contains either apple OR orange OR pear, but NOT the file path.
But there is one more FINDSTR option: /V. This option inverts the result output to handle STDOUT. So output are the lines on which none of the 3 regular expressions produce a positive match.
The command FOR processes each line output by FINDSTR used as negative filter for output of DIR and runs for each line the command DEL respectively ECHO without splitting the line up into space/tab separated strings because of delims=.
And that's it.
It is necessary to prevent the batch file from deletion if being stored in the directory tree processed by command DIR. This can be achieved most easily with setting read-only attribute on batch file as command DEL does not delete files with read-only attribute set.
Example:
#echo off
rem Prevent batch file from deletion by setting read-only attribute on batch file.
%SystemRoot%\System32\attrib.exe +r "%~f0"
for /F "delims=" %%I in ('dir * /A-D /B /S 2^>nul ^| %SystemRoot%\System32\findstr.exe /I /R /V /C:"apple[^\\]*$" /C:"orange[^\\]*$" /C:"pear[^\\]*$"') do del "%%I"
rem It is safe to remove read-only attribute from batch file.
%SystemRoot%\System32\attrib.exe -r "%~f0"
The batch code above has no ECHO before command del and therefore really deletes files on execution.
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.
attrib /?
del /?
dir /?
echo /?
findstr /?
for /?
rem /?
Read also the Microsoft article about Using Command Redirection Operators for an explanation of | and 2>nul.

DELTREE command windows 10 replacement [duplicate]

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