It is not possible with a single command, but with a single command line.
I would do this:
cd /D "C:\Test" && rd /S /Q "C:\Test"
This first changes into the destination root directory. The &&
operator lets the following command execute only when the preceding one succeeded. Then the directory and all its contents is attempted to be deleted; for the contents it works fine, but for the root itself, the error The process cannot access the file because it is being used by another process.
because of the preceding cd
command. This error message (and also others) can be suppressed by appending 2> nul
to the rd
command:
cd /D "C:\Test" && rd /S /Q "C:\Test" 2> nul
If you want the original working directory to be restored, use pushd
/popd
rather than cd
:
pushd "C:\Test" && (rd /S /Q "C:\Test" 2> nul & popd)
The advantage of this method over deletion and recreation (like rd /S /Q "C:\test" && md "C:\Test"
) is that the attributes, the owner and the security settings of the root directory are not lost.
Alternatively, you could do the following, which is more complicated but avoids suppression of errors:
del /S /Q "C:\Test\*.*" & for /D %%D in ("C:\Test\*") do @rm /S /Q "%%~D"
This first deletes all files that reside in the root directory, then it loops through all immediate sub-directories and deletes one after another. The root directory itself is never touched.