删除基于DateCreated的文件或包含日期的文件名

时间:2017-03-12 18:51:39

标签: vbscript scripting

我必须根据文件名删除数据。这就是文件的样子:

  

Nostro_BO_FCC_130317.csv [130317是创建日期]
  Nostro_BO_FCC_120317.csv
  Nostro_BO_FCC_110317.csv
  Nostro_BO_FCC_100317.csv
  Nostro_BO_FCC_090317.csv

这是数据所在的位置:D:\BDI\CTS\Data\Nostro\BO FCC\

我已经开发了VBScript来删除文件,但它根本不起作用。我想要的是删除自当前日期(2017年3月13日)以来2天以下的文件。

这是我的VBScript:

Dim infolder
Dim ad, intcount, i, str, Postdate, Uploaddate, fileExists, ExpireDate
Dim sql_query, rs, rsU
Dim ObjFSO, objFile, OFile, OfPath, osf, MM, DD 

Set ad = CreateObject("ADODB.Connection")
ad.Provider = "sqloledb"

If Len(Month(varDate)) = 1 then
    MM = "0" & Month(varDate)
Else
    MM = Month(varDate)
End If

If Len(Day(varDate)) = 1 then
    DD = "0" & Day(varDate)
Else
    DD = Day(varDate)
End If

PostDate = Year(varDate) & MM & DD
Uploaddate = DD & MM & Right(Year(varDate), 2)
ExpireDate = CDate(DD) < Date - 1 & MM & Right(Year(varDate), 2)

ad.CursorLocation = 3
ad.Open propstr

Set osf = CreateObject("Scripting.FileSystemObject")
OfPath = "D:\BDI\CTS\Data\Nostro\BO FCC\"

'this below my logic steven
Set infolder = osf.GetFolder(OfPath)
Set OFile = Nothing

fileExists = True
fullfilename = "Nostro_BO_FCC_"& Uploaddate &".csv"

'create file if not exits and delete if exits then create again
If Not osf.FileExists(OFPath & fullfilename) Then
    Set OFile = osf.CreateTextFile(OFPath & fullfilename, True)
    Set OFile = Nothing
End If

For Each file In infolder.Files
    If DateDiff("d", file.DateCreated, Date) < Date -2 Then
    '    oFSO.DeleteFile(oFile) 
    'If osf.FileExists(OfPath & "Nostro_BO_FCC_" & ExpireDate & ".csv") Then
        'osf.DeleteFile OfPath & "Nostro_BO_FCC_" & ExpireDate & ".csv"
        file.Delete(True)
    End If
Next

1 个答案:

答案 0 :(得分:1)

CDate(DD) < Date -1 & MM & Right(Year(varDate),2)不会做你显然希望它做的事情。我已经告诉过你,在回答你之前使用类似结构的问题时。

如果要将日期字符串与<>运算符进行比较,则字符串必须采用字符串顺序和日期顺序相同的格式。您的DDMMYY格式不是这种情况。因此,您基本上有两个选择:

  • 由于您有少量有效日期,因此您可以构建参考文件名:

    Function dd(s) : dd = Right("00" & s, 2) : End Function
    
    d1 = Date
    d2 = d1 - 1
    d3 = d1 - 2
    
    fn1 = "Nostro_BO_FCC_"& dd(Day(d1)) & dd(Month(d1)) && Right(Year(d1), 2) &".csv"
    fn2 = "Nostro_BO_FCC_"& dd(Day(d2)) & dd(Month(d2)) && Right(Year(d2), 2) &".csv"
    fn3 = "Nostro_BO_FCC_"& dd(Day(d3)) & dd(Month(d3)) && Right(Year(d3), 2) &".csv"
    

    并删除名称中不包含的所有文件:

    For Each f In infolder.Files
      If f.Name <> fn1 And f.Name <> fn2 And f.Name <> fn3 Then
        f.Delete
      End If
    Next
    
  • 更通用的方法是从每个文件名解析日期:

    a  = Split(osf.GetBaseName(f), "_")
    ds = a(UBound(a))
    d  = DateSerial(Mid(ds, 5, 2), Mid(ds, 3, 2), Mid(ds, 1, 2))
    

    并删除日期低于参考日期的所有文件:

    refDate = Date - 2
    
    For Each f In infolder.Files
      ...
      If d < refDate Then
        f.Delete
      End If
    Next
    

修改:如果您想比较文件&#39;创建日期与您可以这样做的参考日期:

refDate = Date - 2

For Each f In infolder.Files
  If f.DateCreated < refDate Then
    f.Delete
  End If
Next