Delete Files and Folders
When creating command prompts or batch files, it is common to want to delete files that have been used as part of the cleanup process.
In command prompt, the commands for deleting files and folders are different.
This article will introduce how to delete files and folders using command prompt. The same can be achieved with batch files.
How to delete specified files
First, let’s introduce how to delete specified files.
Use the del
command to delete files.
If no options are specified, there will be no confirmation message displayed at runtime, and the file will be completely deleted without being stored in the recycle bin.
Executing from Command Prompt
Here is an example of deleting a file named “disposable.txt” saved in My Documents from the command prompt.
Executing from a batch file
@echo off
setlocal
set FOLDER=%userprofile%\Documents\
set FILE=disposable.txt
del %FOLDER%%FILE%
endlocal
exit
Options for the del command
By specifying the /p option, you can prompt the user to confirm whether the command should be executed.
Note that for batch files, the process will stop at that point, so be careful.
Specifying multiple files
Multiple files can be specified by separating them with spaces, commas, or semicolons.
Executing from Command Prompt
Executing from a batch file
@echo off
setlocal
set FOLDER=%userprofile%\Documents\
set FILE1=disposable.txt
set FILE2=deletable.txt
del %FOLDER%%FILE1% %FOLDER%%FILE2%
endlocal
exit
Deleting Folders
Next, we will introduce how to delete folders.
To delete a folder, use the rmdir
command. It is named to pair with mkdir
, so it should be easy to remember.
Please refer to this article for information on mkdir
.
There is also a shortened command called rd
, but it performs the same operation.
If no options are specified, this command can only delete empty folders.
If you want to delete everything in the folder, including files and other folders, you need to specify the options described below.
Executing from Command Prompt
Here is an example of deleting a folder named “disposable” saved in My Documents.
Executing from a batch file
Executing from a batch file
@echo off
setlocal
set PARENT=%userprofile%\Documents\
set DIR=disposable
rmdir %PARENT%%DIR%
endlocal
exit
Options for the rmdir command
Delete files in a folder
To delete all files in a folder, including those in subfolders, use the /s option.
If you use this option, a confirmation message will be displayed at runtime.
If you want to hide this confirmation message, specify the /q option.