2012年1月19日 星期四

每天自動刪除過期檔案(Delete Files over than n days)

File Server 雖是儲存空間,但也不必要永久存放,如果已經進磁帶備份後,很多參考用的大檔案是可以刪除的。

研究了一下 VBScript 自動刪除的機制,將下面的.vbs File 加到Server 的Schedule Tasks ,再加上絕對路徑當參數,就可以自動刪除了。

------------------ 以下作成一個 delFolderFilesOverThan60days.vbs --------


' 指定所有變數必須事先宣告才能使用
Option Explicit
 
' 宣告變數
Dim FSO, agoDays, modifiedDate, delFolder  ,myArgs

'If WScript.arguments.length <> 0 Then
' WScript.quit  
'End If

' 建立檔案系統物件(File System Object)
Set FSO = CreateObject("Scripting.FileSystemObject")

' 請將下面的變數值換成你要的
' 指定 n 天前的檔案,現在是 3 天前
agoDays = 60
' 取得檔案的修改日期
modifiedDate = DateAdd("d", -agoDays, Date)  

Set myArgs = WScript.arguments

' 欲刪除檔案所在之目錄    
delFolder = myArgs(0)

' 呼叫刪除檔案的子程序
DelFilesInFolder FSO.GetFolder(delFolder)    

' 刪除檔案的子程序
Sub DelFilesInFolder(folder)
  ' 宣告變數
  Dim file, subFolder
 
  ' 找出目前所在目錄內所有的檔案
  For Each file In folder.Files
      ' 檢查檔案日期是否符合條件,若符合,就刪除
      If ((file.DateLastModified <= modifiedDate)) Then
          file.delete
      End If
  Next
 
  ' 如果遇到子目錄,也要進去檢查並刪除
  For Each subFolder in folder.SubFolders
      DelFilesInFolder subFolder
Next
End Sub  
 
'WScript.Echo("作業執行完畢:" & Date & " " & Time)

----------------------------------

程式的參考出處:

http://ithelp.ithome.com.tw/question/10009001
http://ithelp.ithome.com.tw/question/10058183