如何确保目录存在且为空?
此
rmdir %1 /s /q & mkdir %1
遭受"访问被拒绝"问题Why does mkdir occasionally give Access Denied?我希望在访问可用之前避免循环风险。
答案 0 :(得分:0)
如果文件夹正在使用,则无法将其删除。如果它没有被使用,你可以先重命名该文件夹然后删除它(这应该处理异步问题)。如果文件夹正在使用中,您可能无法删除它,但您可以删除该内容。
试一试。不是理想的解决方案,但应该处理通常的情况
@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
答案 1 :(得分:0)
一种可能的方法:
md empty
robocopy /e /purge empty %1