0

How may I ensure a directory exists and is empty?

This

rmdir %1 /s /q & mkdir %1

suffers from the "Access is denied" issue Why does mkdir occasionally give Access Denied? and I want avoid the risk of looping until access is available.

Community
  • 1
  • 1
ChrisJJ
  • 2,191
  • 1
  • 25
  • 38
  • Other processes are liable to be interested into that directory as well, particularly anti-malware and search indexers. They'll open files with delete sharing, the directory won't actually disappear until the last handle is closed. How long that takes is unpredictable. There is no point in doing this at all, just use del *.* – Hans Passant Aug 21 '14 at 18:00
  • @Hans. Thanks. Do yo have solution using del that is clean e.g. not causing false errorlevel from mkdir when one exists? The obvious solutions seem likewise prone to AV interference. – ChrisJJ Aug 22 '14 at 14:42
  • Hard to guess what you are talking about. If you use `del *.*` to clean a directory then you of course don't need mkdir anymore. It is still there. – Hans Passant Aug 22 '14 at 14:49
  • @Hans. It is not necessarily still there. It may not have been there previously. – ChrisJJ Aug 24 '14 at 19:31

2 Answers2

0

You can not remove a folder if it is in use. If it is not in use, you can first rename the folder and then delete it (this should handle the async problem). And maybe you can not delete the folder if it is in use, but you can remove the content.

Give it a try. Not a ideal solution but should handle the usual cases

@echo off
    setlocal enableextensions disabledelayedexpansion

    call :resetFolder ".\test"
    if errorlevel 1 (
        echo folder is in use and can not be reset
    ) else (
        echo folder has been reset
    )

    endlocal
    exit /b

:resetFolder folder
    setlocal disabledelayedexpansion
    set "ts=%random%%random%%random%"
    for %%a in ("%~1\.") do (

        rem Rename the folder and then delete it
        if exist "%%~fa\" ren "%%~fa" "%%~nxa.%ts%.tmp" 2>nul && (
            start /b "" cmd.exe /q /c "rmdir /s /q "%%~dpa%%~nxa.%ts%.tmp" >nul 2>nul"
        )

        rem If rename failed, folder content is in use. Try to remove as much content as possible
        if exist "%%~fa\" ( rmdir /s /q "%%~fa" >nul 2>nul )

        rem Test if the folder has been removed, has no content or still contains data
        if exist "%%~fa\" (
            dir /a /b "%%~fa" | find /v "" > nul && exit /b 1
        ) else (
            mkdir "%%~fa" >nul 2>nul || exit /b 1
        )
    )
    exit /b 0
MC ND
  • 69,615
  • 8
  • 84
  • 126
0

One possible approach:

md empty
robocopy /e /purge empty %1
Harry Johnston
  • 35,639
  • 6
  • 68
  • 158