Reputation: 13
I want to delete a specific directory on Windows. I use the code below. It works fine. I want to put the .bat file I made for this process in that directory. Naturally, the .bat file is also deleted. I want the .bat file to be excluded from this deletion. What should I do with the code?
Echo batch file delete folder
@RD /S /Q "D:\testfolder"
Upvotes: 0
Views: 1328
Reputation: 1463
All you have to do is to lock your batch file, by opening a dummy read handle to it.
echo The batch file wont be deleted because it is locked by a dummy input redirection.
rd /s /q "D:\testfolder" 9<"%~f0"
Naturally, an error message will be shown by the rd
command, because there is at-least one file in the target directory (your own batch file) which can not be deleted. You can hide that message by redirecting the standard error stream to the nul
device:
rd /s /q "D:\testfolder" 9<"%~f0" 2>nul
Upvotes: 1
Reputation: 34989
I would walk through the items in the folder whose contents you want to delete, remove one after another, except its name equals the name of the batch file:
rem // Change into target directory:
pushd "%~dp0." && (
rem /* Loop through immediate children of the target directory, regarding even
rem hidden and system items; to ignore such (replace `/A` by `/A:-H-S`): */
for /F "delims= eol=|" %%I in ('dir /B /A "*"') do (
rem // Check name of current item against name of this batch script:
if /I not "%%~nxI"=="%~nx0" (
rem /* Assume the current item is a sub-directory first (remove by `rd`);
rem when removal fails, try to delete it as a file (done by `del`): */
rd /S /Q "%%I" 2> nul || del /A /F "%%I"
)
)
rem // Return from target directory:
popd
)
Upvotes: 0
Reputation: 38719
There are several ways to achieve your task.
The method, (especially as you generally remove directories with one command, and delete files with another), is to identify the files and subdirectories separately. First identify the subdirectories and remove those, using the RD
command, then delete all files except for the batch file itself, %0
:
You could do that in one line using the ForFiles
utility:
@%SystemRoot%\System32\forfiles.exe /P "%~dp0." /C "%SystemRoot%\System32\cmd.exe /C If @IsDir==TRUE (RD /S /Q @File) Else If /I Not @file == \"%~nx0\" Del /A /F @File"
Or you could use a For
loop, with the Dir
command:
@For /F Delims^=^ EOL^= %%G In ('Dir /B /A "%~dp0"') Do @If "%%~aG" GEq "d" (RD /S /Q "%%G") Else If /I Not "%%G" == "%~nx0" Del /A /F "%%G"
Please note that you can only remove/delete items for which you have the required permissions.
Upvotes: 0