using VB to move oldest file to a new folder

Hi, I have a little script that runs as a scheduled task  The purpose of the task is to move the oldest files in a specific directory into a new directory.  This works as expected when there are files in the directory. However if there are no files in the directory then I get an error message.  Attached below is the script that I have used.

Set objFSo = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("C:\MAS\Company\")

Set colFiles = objFolder.Files

dtmOldestDate = Now
 
For Each objFile in colFiles
    If objFile.DateCreated < dtmOldestDate Then
        dtmOldestDate = objFile.DateCreated
        strOldestFile = objFile.Path
    End If
Next

objFSO.MoveFile strOldestFile, ("C:\MAS\Company\FTP\")

Any help would be much appreciated.
cablandAsked:
Who is Participating?
 
oBdACommented:
Check the number of files returned:
Set objFSo = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("C:\MAS\Company")

Set colFiles = objFolder.Files
If colFiles.Count > 0 Then
	dtmOldestDate = Now
	For Each objFile in colFiles
		If objFile.DateCreated < dtmOldestDate Then
			dtmOldestDate = objFile.DateCreated
			strOldestFile = objFile.Path
		End If
	Next
	objFSO.MoveFile strOldestFile, ("C:\MAS\Company\FTP\")
End If

Open in new window

0
 
cablandAuthor Commented:
Hi, this works a treat, I have one more requirement.  I only want it to move the file it is older than one minute.  Is this a simple adjustment?
0
 
oBdACommented:
I added some output and commented the actual "MoveFile" command for easier testing; simply remove or comment the Wscript.Echo lines if you don't want them:
Set objFSo = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("C:\MAS\Company")
intMinFileAge = 1

Set colFiles = objFolder.Files
If colFiles.Count > 0 Then
	dtmOldestDate = Now
	For Each objFile in colFiles
		If objFile.DateCreated < dtmOldestDate Then
			dtmOldestDate = objFile.DateCreated
			strOldestFile = objFile.Path
		End If
	Next
	intFileAge = DateDiff("n", dtmOldestDate, Now)
	Wscript.Echo "Oldest File: '" & strOldestFile & "', " & intFileAge & " minutes old."
	If intFileAge > intMinFileAge Then
		Wscript.Echo "Moving to new location ..."
		REM objFSO.MoveFile strOldestFile, ("C:\MAS\Company\FTP\")
	Else
		Wscript.Echo "Not more than " & intMinFileAge & " minutes old, doing nothing."
	End If
Else
	Wscript.Echo "No files found."
End If

Open in new window

0
 
cablandAuthor Commented:
Sorry it has taken so long to close this off.  The first example given does exactly what I need it to do.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.