清理目录,但排除子目录

时间:2014-10-29 07:28:09

标签: svn batch-file powershell-v4.0

我有子目录的目录

C:\temp
├───.svn
│   └───gg
├───common
│   ├───.svn
│   │   └───fff
│   └───ggggg
└───todel
    ├───gffgf
    └───jhj

我需要清除c:\temp,但保留.svn文件夹,不加修改内容。 下面描述的方法不适用于子目录(在我的情况下是common.svn) 我希望得到以下结构

C:.
├───.svn
│   └───gg
└───common
    └───.svn
        └───fff

Delete all files and folders but exclude a directory 批处理方法概述也没有给出结果,因为cmd rd命令在父文件夹删除期间也不会意识到子目录。 我已经完成了以下内容: Delete all folders except.... (*.BAT) Exclude a folder inside temp when executing a del batch file

4 个答案:

答案 0 :(得分:2)

如果正确使用递归CALL,则需要很少的代码。

小心这个脚本!如果滥用会造成伤害。

脚本不能驻留在要清理的根层次结构中#34;

当前目录不能是要删除的文件夹之一。

如上所述,该脚本不考虑Hidden,System或ReadOnly文件或文件夹。

<强> PURGE.BAT

@echo off
setlocal disableDelayedExpansion
if /i "%~nx1" equ ".svn" exit /b 1
del /q "%~1.\*"
set "keep=0"
for /d %%F in ("%~1.\*") do call "%~f0" "%%~fF" && rd "%%F" || set "keep=1"
exit /b %keep%

编辑:代码已经过编辑,可以正常使用以下所有用例:(假设当前目录为&#34; c:\ test&#34;)

purge.bat "c:\temp"
purge.bat "c:\temp\"
purge.bat "d:\"
purge.bat "d:"

有关详细信息,请参阅How to safely append a file name to a Windows folder path argument?

答案 1 :(得分:1)

@echo off
    setlocal enableextensions disabledelayedexpansion

    set "folder=c:\temp"

    rem Temporary files
    set "folderList=%temp%\%~nx0.folder.tmp"
    set "SVNList=%temp%\%~nx0.svn.tmp"
    set "notSVNList=%temp%\%~nx0.notsvn.tmp"

    rem Retrieve the list of all folders
    dir /s /ad /b "%folder%\*" | sort > "%folderList%"

    rem Retrieve the list of svn folders
    findstr /i /r /c:"\\\.svn[\\]" /c:"\\\.svn$" "%folderList%" > "%SVNList%"

    rem Retrieve the list of not svn folders
    findstr /v /i /r /c:"\\\.svn[\\]" /c:"\\\.svn$" "%folderList%" > "%notSVNList%"

    rem For each folder not in svn list
    for /f "usebackq delims=" %%a in ("%notSVNList%") do (
        rem If the folder exist test if it is a parent of a svn folder 
        rem If it is a parent delete its contents else remove the folder
        if exist "%%a" findstr /l /b /c:"%%a\\" "%SVNList%" >nul && ( 
            del /q "%%a\*" 
        ) || ( 
            rd /s /q "%%a" 
        )
    )

    rem Remove remaining files in starting folder
    del /q "%folder%\*" >nul 2>nul 

    rem Remove temporary files
    del /q "%folderList%" >nul 2>nul 
    del /q "%SVNList%" >nul 2>nul 
    del /q "%notSVNList%" >nul 2>nul 

答案 2 :(得分:1)

@echo off
setlocal EnableDelayedExpansion

rem Traverse the tree in top-down order and get subdirectories that could be deleted
set tos=0
for /D /R "C:\temp" %%a in (*) do (
   set "subdir=%%a"
   if "!subdir:\.svn=!" equ "%%a" (
      set /A tos+=1
      set "stack[!tos!]=%%a"
   )
)

rem Process subdirectories in opposite (bottom-up) order
for /L %%i in (%tos%,-1,1) do (
   rem Delete all files in the subdirectory
   del /Q "!stack[%%i]!\*.*"
   rem And remove the subdirectory if it becomes empty
   rd "!stack[%%i]!" 2>NUL
)

答案 3 :(得分:0)

未经测试,但这样的事情应该有效:

svn move temp\* .
svn delete temp