删除早于n天的文本文件的VBS脚本

时间:2014-10-23 08:46:48

标签: vbscript

我想删除某个目录中已在n天前创建的所有文本文件。把它想象成一个看家的任务。

我目前有一个脚本可以做得很好,但它使用文件的creatin日期。我现在必须检查文件名中的日期,并删除与脚本参数匹配的所有文本文件。

' Objective: To delete old files from a given folder and all subfolders below
'
'
' Format: cscript deloldfiles.vbs {DriveLetter:\FolderName} {#ofDays}
'     or: cscript deloldfiles.vbs {\\servername\FolderName} {#ofDays}
' Example: cscript deloldfiles.vbs c:\dba\log 3
'    (deletes files older than 3 days from the \dba\log file on drive C:)

Set objArgs = WScript.Arguments
FolderName =objArgs(0)
Days=objArgs(1)

set fso = createobject("scripting.filesystemobject")
set folders = fso.getfolder(FolderName)
datetoday = now()
newdate = dateadd("d", Days*-1, datetoday)
wscript.echo "Today:" & now()
wscript.echo "Started deleting files older than :" & newdate 
wscript.echo "________________________________________________"
wscript.echo ""
recurse folders 
wscript.echo ""
wscript.echo "Completed deleting files older than :" & newdate 
wscript.echo "________________________________________________"

sub recurse( byref folders)
  set subfolders = folders.subfolders
  set files = folders.files
  wscript.echo ""
  wscript.echo "Deleting Files under the Folder:" & folders.path
  wscript.echo "__________________________________________________________________________"
  for each file in files
    if file.datelastmodified < newdate then
      wscript.echo "Deleting " & folders.path & "\" & file.name & " last modified: " & file.datelastmodified
      on error resume next
' === to test this script but not actually delete files, comment out the next line ===
    file.delete
    end if

  next  

  for each folder in subfolders
    recurse folder
  next  

  set subfolders = nothing
  set files = nothing

end sub

TEXTFILES:

SynchroniseUsersFromBBS_LOG_20140910_412.txt
SynchroniseUsersFromBBS_LOG_20140810_1023.txt
SynchroniseUsersFromBBS_LOG_20141010_1523.txt
SynchroniseUsersFromBBS_LOG_20141022_1023.txt
SynchroniseUsersFromBBS_LOG_20141023_1023.txt

任何想法如何做到这一点?

1 个答案:

答案 0 :(得分:2)

如果您的样本名称具有代表性,您可以使用Mid()和DateSerial()从文件名中获取日期(具有正确的类型):

>> s = "SynchroniseUsersFromBBS_LOG_20140910_412.txt"
>> d = DateSerial(CLng(Mid(s, 29, 4)), CLng(Mid(s, 33, 2)), CLng(Mid(s, 35, 2)))
>> WScript.Echo s, "=>", TypeName(d), d
>>
SynchroniseUsersFromBBS_LOG_20140910_412.txt => Date 10.09.2014
>>

如果没有,您将不得不使用RegExp - 基于对文件名的更详细描述。

<强> PS:

没有RegExp,但通过InStr(Rev)获得更大的灵活性:

>> s = "FromBBS_LOG_20140910_412.txt"
>> p = InStrRev(s, "_") - 8
>> d = DateSerial(CLng(Mid(s, p, 4)), CLng(Mid(s, p + 4, 2)), CLng(Mid(s, p + 6, 2)))
>> WScript.Echo s, "=>", TypeName(d), d
>>
FromBBS_LOG_20140910_412.txt => Date 10.09.2014
>>