如何使用批次腳本查找具有特定名稱的所有資料夾並刪除除兩個文件之外的所有內容?

如何使用批次腳本查找具有特定名稱的所有資料夾並刪除除兩個文件之外的所有內容?

要清理項目,我需要找到palette-library從批次腳本檔案的當前位置開始命名的所有(子)資料夾,然後刪除除名為 的資料夾penstyle-opacity textures和名為 的檔案之外的所有內容penstyle-opacity.plt。我使用Windows 7。

我在谷歌上搜尋了很多,但到目前為止我只找到了一些片段,可以搜尋、找到和刪除資料夾的所有內容,或者從預定義位置刪除除特定文件之外的所有內容。但是,我無法將兩者放在一起。

答案1

也許不是最優雅的方式,但您可以先透過遮罩存檔文件,然後擦除文件樹,然後使用路徑解壓縮存檔。

例如:

7z a -r my_archive penstyle-opacity.plt

或者:

7z a -r my_archive "palette-library\penstyle-opacity textures\penstyle-opacity.plt"

嘗試並選擇更適合您的。

答案2

第一個參數是要刪除的資料夾,其餘是檔案例外列表,允許使用通配符,將刪除除與清單相符的檔案之外的所有資料夾及其子資料夾。技巧是先隱藏所有異常,然後在刪除後取消隱藏它們。

@echo off

rem test routine
call :DELDIREXCEPT "c:\testfolder" "pru 2" "must leave.docx" *.jpg *.png *.exe


GOTO :FIN

REM   * * * *  SUBROUTINES FROM HERE  * * * *
REM

:DELDIREXCEPT
  rem deletes folder except a list of files
    rem  ~ removes quotes
  set delDir=%~1
  if not exist "%delDir%" goto :FIN
  pushd %delDir% 2>nul || goto :FIN
    rem get rest of params
  shift
  rem https://stackoverflow.com/questions/357315/how-to-get-list-of-arguments/34920539#34920539
  rem Delayed expansion disabled in order not to interpret "!" in param values;
  rem however, if a param isn't quoted, chars like "^", "&", "|" get interpreted
  setlocal disabledelayedexpansion
  set param_0=0
  :repeat
    set "lastparam=%~1"
    set /a param_0+=1
    if defined lastparam (
      set "param_%param_0%=%lastparam%"
      echo Hide: "%lastparam%"
      attrib "%lastparam%" +h /s /d 2>nul
      shift
      goto :repeat
    ) else set /a param_0-=1

  setlocal enabledelayedexpansion
  echo .. deleting %delDir%
  del /s /q /a-h *.* 2> NUL
  echo ...
  :: unhide arguments
  for /l %%Z in (1 1 %param_0%) do (
    echo/ unHide: "!param_%%Z!"
    attrib /s /d "!param_%%Z!" -h 2>nul
  )
  popd
goto :FIN
REM END DELDIREXCEPT


:FIN

相關內容