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.
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.
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