简体   繁体   中英

How to delete files recursively

I have the directory structure /foo/bar/fooBar/.. . I want to write a Windows command where I can mention the path till foo directory and it deletes all the files and directory recursively in /foo, but it should NOT delete the foo directory.

I have been using rmdir /q /s [path to foo] but this command deletes the foo directory as well. Let me know if there is any command(s) to accomplish this.

rd /s /q /path/to/foo
md /path/to/foo
del /f /s /q DirectoryWhichContainsFilesToDelete/\*

This will delete all files in the folder DirectoryWhichContainsFilesToDelete without deleting the folder itself. Have fun :)

I had been scratching my head on this one as well. It is easy enough to create a for loop that uses rmdir however it leaves behind folders that have spaces in the long names. It is possible to manipulate a dir list and get the 8.3 filenames however here is a much simpler solution.

Create an empty folder then;

robocopy \empty_folder \folder_with_sub_folders /PURGE

All subfolders & files will be deleted.

del X /f /s /q 
rd X /s /q 

this WILL remove the ROOt directory though. make it again with

 md X

or make a copy of it first.

otherwise you'll have to do batch funkiness

 dir X /ad /b

will give you a list of the immediate subdirectories of X. you can work out the rest

I was looking for a simple command to delete all files in a directory recursively but leaving the directory structure unchanged. So, maybe this could be interesting ;)

for /f "delims=" %i in ('dir /B /S /A:-DH') do @del /F /Q /A:H "%i"

The command 'dir /B /S /A:-D' lists only files (/A:-D) in current directory recursively (/S) without 'dir' summary report (/B). The 'for' loops through each full line (/delims=) and executes the delete command, forced and quiet. I additionally used the hidden flag (/H) both for listing and deletion for some mysterious (eg thumbs.db) files.

尝试使用Powershell:

powershell -Command "Remove-Item '\foo\*' -Recurse -Force"

deltree / foo / *应该可以正常工作。

I have used this in a batch file in the past. It uses a for loop to navigate the directory structure.

Here I remove the cvs sub directories off of a tree, needed when copying from one branch to another.

@echo off
if /I exist CVS. rd CVS /s /q >nul
for /F %%z in ('dir cvs /ad /s /b') do echo %%z && rd /s /q %%z
echo Batchfile %0 is complete

To prevent deleting of the foo directory try change directory to foo prior to the delete such as:

cd c:\\foo rd /s /qc:\\foo

This will delete all the files and folders under foo but NOT foo. An error message will be displayed as follow "The process cannot access the file because it is being used by another process."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM