abhayk
abhayk

Reputation: 287

how to delete subfolders without deleting parent folder and child folder?

For this type of directory structure:

\\rdwlhsdevserver\root\user1\folders\testdat.txt
\\rdwlhsdevserver\root\abhay\testdat.txt
\\rdwlhsdevserver\root\testuser\folders1\folder2\testdat.txt
\\rdwlhsdevserver\root\devadmin\input\testdat.txt
\\rdwlhsdevserver\root\admin\testdata\testdat.txt

I know that I can use del /s /q \\rdwlhsdevserver\root\* to delete files from parent folder and all sub-folders. But I want to delete all folders and files except \\rdwlhsdevserver\root\<folder>\.

After running cmd output should be like:

\\rdwlhsdevserver\root\user1\
\\rdwlhsdevserver\root\abhay\
\\rdwlhsdevserver\root\testuser\
\\rdwlhsdevserver\root\devadmin\
\\rdwlhsdevserver\root\admin\

Upvotes: 0

Views: 2096

Answers (2)

MC ND
MC ND

Reputation: 70923

pushd "\\rdwlhsdevserver\root" && (
    for /d %%a in (*) do ( cd "%%a" && ( 2>nul rmdir . /s /q & cd .. ) )
    del /f /q *
    popd
) 

This will change the current active directory (pushd) to the target directory and if there are no problems (conditional execution operator &&) for each folder (for /d) change to it (cd), remove its contents (rmdir) and return to the parent folder. Once done, remove (del) the files inside the root folder and restore the initial active directory.

Why not change the inner for to for /d %%a in (*) do rmdir "%%a" /s /q ? Because this will also remove the folder. But if we first make the folder the current active directory (cd) we will be able to delete its contents but not the folder itself as it is in use (the 2>nul is a redirection of the stderr stream to nul to hide the error in the rmdir saying it can not remove the folder because it is in use)

Upvotes: 2

aschipfl
aschipfl

Reputation: 34899

You need to iterate over all sub-directories of \\rdwlhsdevserver\root\ using a for /D loop, then loop over each sub-directory's sub-directories again by another for /D loop, then apply the rmdir (or rd) command on each of the returned items, like this:

for /D %%J in ("\\rdwlhsdevserver\root\*") do (
    for /D %%I in ("%%~J\*") do (
        rmdir /S /Q "%%~I"
    )
)

Or in command prompt directly:

for /D %J in ("\\rdwlhsdevserver\root\*") do @for /D %I in ("%~J\*") do @rmdir /S /Q "%~I"

For the sake of overall performance, if you want to delete directories and files, I recommend to do the above directory removal before the file deletion (del /S /Q "\\rdwlhsdevserver\root\*"). Note that your del command line also deletes files located in the directory \\rdwlhsdevserver\root\.

Upvotes: 1

Related Questions