2013-11-22 303 views
1

我試圖寫一個Windows腳本(用於Win7/Server 2008),刪除比特定日期更早的文件,同時保留最新的文件,無論年齡。Windows批處理文件,從目錄中刪除文件,但保留每個目錄中的最新文件

Perforce的存儲由目錄中的封裝它版本的服務器或代理上的二進制文件。

例如,如果我在服務器上存儲image.jpg並更新兩次,它會將它存儲在一個像「image.jpg,d」這樣的目錄中,裏面帶有編號的gzip文件。

例如

c:\depot\1\image.jpg,d\123.gz | last modified: 9/1/2013 
c:\depot\1\image.jpg,d\124.gz | last modified: 10/1/2013 
c:\depot\1\image.jpg,d\125.gz | last modified: 11/1/2013 
c:\depot\2\image.jpg,d\123.gz | last modified: 9/1/2013 
c:\depot\2\image.jpg,d\124.gz | last modified: 10/1/2013 
c:\depot\2\image.jpg,d\125.gz | last modified: 11/1/2013 

在這種情況下,如果我跑了14天以上文件的標準FORFILES刪除腳本,所有六個文件將被刪除。我想找一份在這種情況下,123.gz和124.gz被除去溶液中,但125.gz在兩個目錄獨處。

如果有這樣的文件夾中的單個文件:

c:\depot\1\hw\images\helloworld.jpg,d\122.gz | last modified 1/1/2013 

它會獨自離開的文件。如果有多個,就會留下最近的一次。

該解決方案類似,但沒有成功與Win7的:How to use forfiles (or similar) to delete files older than n days, but always leaving most recent n

回答

0

更改"c:\server\folder"的基本位置,並運行此:

代碼旨在讓每一個文件夾中的最新修改的文​​件,並刪除其餘的部分。

它只會將del命令回顯到屏幕上,所以請將echo del更改爲del並再次運行它,以便在它按照您的要求進行操作時發揮作用。

@echo off 
for /d /r "c:\server\folder" %%a in (*) do (
    pushd "%%a" && (
     echo processing "%%a" 
     for /f "skip=1 delims=" %%b in ('dir /b /a-d /o-d') do echo del "%%b" 
    popd 
    ) 
) 
0
@echo off 

    setlocal enableextensions 

    set "_depot=c:\depot" 

    rem Enumerate all the directories under depot, 
    rem and retrieve only those that end with ,d 
    for /f "tokens=*" %%d in ('cmd /q /c "(for /r "%_depot%" %%a in (.) do echo "%%~fa")" ^| findstr /e ",d"""') do (
     rem list the files in selected directory, ordered by creation date descending 
     rem skip the first file in list and delete the rest 
     for /f "tokens=* skip=1" %%f in ('dir /a-d /tc /o-d /b "%%d\*.gz" 2^>nul') do (
      rem WARNING !!! 
      rem DELETING FILES. Remove echo when sure it works as needed 
      rem WARNING !!! 
      echo del "%%~fd\%%f" 
     ) 
    ) 
    endlocal 
相關問題