Batch file. Delete all files and folders in a directory

前端 未结 14 1245
无人共我
无人共我 2020-11-30 19:20

I want to have a batch file that will delete all the folders and files in my cache folder for my wireless toolkit.

Currently I have the following:

cd         


        
相关标签:
14条回答
  • You could use robocopy to mirror an empty folder to the folder you are clearing.

    robocopy "C:\temp\empty" "C:\temp\target" /E /MIR
    

    It also works if you can't remove or recreate the actual folder.

    It does require an existing empty directory.

    0 讨论(0)
  • 2020-11-30 19:27

    You cannot delete everything with either rmdir or del alone:

    • rmdir /s /q does not accept wildcard params. So rmdir /s /q * will error.
    • del /s /f /q will delete all files, but empty subdirectories will remain.

    My preferred solution (as I have used in many other batch files) is:

    rmdir /s /q . 2>NUL
    
    0 讨论(0)
  • 2020-11-30 19:28

    You can do this using del and the /S flag (to tell it to recurse all files from all subdirectories):

    del /S C:\Path\to\directory\*
    

    The RD command can also be used. Recursively delete quietly without a prompt:

    @RD /S /Q %VAR_PATH%
    

    Rmdir (rd)

    0 讨论(0)
  • 2020-11-30 19:30

    I just put this together from what morty346 posted:

    set folder="C:\test"
    IF EXIST "%folder%" (
        cd /d %folder%
        for /F "delims=" %%i in ('dir /b') do (rmdir "%%i" /s/q || del "%%i" /s/q)
    )
    

    It adds a quick check that the folder defined in the variable exists first, changes directory to the folder, and deletes the contents.

    0 讨论(0)
  • 2020-11-30 19:32

    Just a modified version of GregM's answer:

    set folder="C:\test"
    cd /D %folder%
    if NOT %errorlevel% == 0 (exit /b 1)
    echo Entire content of %cd% will be deleted. Press Ctrl-C to abort
    pause
    
    REM First the directories /ad option of dir
    for /F "delims=" %%i in ('dir /b /ad') do (echo rmdir "%%i" /s/q)
    
    REM Now the files /a-d option of dir
    for /F "delims=" %%i in ('dir /b /a-d') do (echo del "%%i" /q)
    
    REM To deactivate simulation mode remove the word 'echo' before 'rmdir' and 'del'.
    
    0 讨论(0)
  • 2020-11-30 19:33

    Use:

    • Create a batch file

    • Copy the below text into the batch file

      set folder="C:\test"
      cd /d %folder%
      for /F "delims=" %%i in ('dir /b') do (rmdir "%%i" /s/q || del "%%i" /s/q)
      

    It will delete all files and folders.

    0 讨论(0)
提交回复
热议问题