Home > Mobile >  VBScript moved and new created file with same date-time
VBScript moved and new created file with same date-time

Time:03-15

I'm using the following code to rotate log files. If the Log.txt file is different than the current date-time (based on file property .DateCreated), the file is moved using the .DateCreated value to rename it and then a new Log.txt file is created but the new file date created value is the same as the moved (archived) file.

If the script is run again a few seconds later it fails to move the Log.txt file as an archived version already exist.

Option Explicit

 Dim objFS: Set objFS = CreateObject("Scripting.FileSystemObject")
 Dim strLogPath: strLogPath = "C:\Logs"
 Dim strLogFQFN: strLogFQFN = objFS.BuildPath(strLogPath, "Log.txt")
 
  If objFS.FileExists(strLogFQFN) <> True Then
   WScript.Quit
  End If

  'As file exists, validate if archive is needed
  Dim objFile: Set objFile = objFS.GetFile(strLogFQFN)

  Dim dtmLog: dtmLog = objFile.DateCreated'DateValue(objFile.DateCreated)
  Dim dtmNow: dtmNow = Now 'Date
  Set objFile = Nothing
  WScript.Echo dtmLog
  WScript.Echo dtmNow
  If (dtmLog <> dtmNow) Then
   Dim tsDate: tsDate = DatePart("yyyy", dtmLog) & "-" & Right("0" & DatePart("m", dtmLog), 2) & "-" & Right("0" & DatePart("d", dtmLog), 2)
   Dim tsTime : tsTime = Right("0" & Hour(dtmLog), 2) & Right("0" & Minute(dtmLog), 2) & Right("0" & Second(dtmLog), 2)
   Call objFS.MoveFile(strLogFQFN, objFS.BuildPath(strLogPath, tsDate & "T" & tsTime & ".txt"))
   Call objFS.CreateTextFile(strLogFQFN, False)
  End If

1st run - Original file Log.txt moved to 2022-03-11T014931.txt and new Log.txt created

1st and 2nd run date-time values and error

Thanks

CodePudding user response:

Based on LesFerch comment I have tested adding a delay of 16 seconds to overcome the default Tunneling cache time and that resolved the issue using the C drive.

Call objFS.MoveFile(strLogFQFN, objFS.BuildPath(strLogPath, tsDate & "T" & tsTime & ".txt"))
WScript.Sleep 16000
Call objFS.CreateTextFile(strLogFQFN, False)
  • Related