Solved

VB Script: Dynamically rename files based on last date modified.

Posted on 2015-02-24
9
86 Views
Last Modified: 2015-02-26
Hello experts,

I am looking for a script that rename files in a specific folder based on the lastdatemodified

Ex: File1.csv--->lastdatetemodified(2014,02,24)
      File2.csv--->lastdatetemodified(2014,12,25)

Result after I run the script
File1_20140224.csv
File2_20141225.csv

Imagine that I modifie now File 1 and I re-run the script.

The result should be the following:
File1_20150224.csv
File2_20141225.csv

Additionally I would like to add the following log loops (for errors, I would like to output a log.txt file):
1-If folder path  doesn't finish "\" add a back slash.
2- If the folder setup in which the script should rename the files doesn't exist echo.Wscript "the Folder with the following path doesn't exist"
3-If the files.count=0 echo.Wscript "Folder doesn't contains files to rename"
0
Comment
Question by:LD16
  • 5
  • 4
9 Comments
 
LVL 65

Expert Comment

by:RobSampson
ID: 40629612
Hi, I think this script should cover all of your requirements.  I have also added some extra checking to make sure that it replaces the date in the file name (on subsequent runs) with the new date modified.

Regards,

Rob.

Set objFSO = CreateObject("Scripting.FileSystemObject")
strFolder = "C:\Temp\Scripts\EE"
strLogFile = "C:\Temp\Scripts\LogFile.txt"
If Right(strFolder, 1) <> "\" Then strFolder = strFolder & "\"
If objFSO.FolderExists(Left(strLogFile, InStr(strLogFile, "\"))) = False Then
	WScript.Echo "Log cannot be created.  " & Left(strLogFile, InStr(strLogFile, "\")) & " does not exist."
Else
	Set objLog = objFSO.OpenTextFile(strLogFile, 8, True)
	WriteOutput Now & ": Script started"
	If objFSO.FolderExists(strFolder) = False Then
		WriteOutput strFolder & " does not exist."
	Else
		Set objFolder = objFSO.GetFolder(strFolder)
		If objFolder.Files.Count = 0 Then
			WriteOutput strFolder & " does not contain any files."
		Else
			For Each objFile In objFolder.Files
				dteModifiedDate = CDate(objFile.DateLastModified)
				strDate = Year(dteModifiedDate) & Right("0" & Month(dteModifiedDate), 2) & Right("0" & Day(dteModifiedDate), 2)
				strBaseName = objFSO.GetBaseName(objFile.Path)
				strExtension = objFSO.GetExtensionName(objFile.Path)
				strNewName = objFolder.Path & "\" & strBaseName & "_" & strDate & "." & strExtension
				If Len(strBaseName) > 9 Then
					If InStrRev(strBaseName, "_") = Len(strBaseName) - 8 Then
						strSuffix = Mid(strBaseName, Len(strBaseName) - 7)
						If IsNumeric(strSuffix) Then
							If IsDate(Left(strSuffix, 4) & "-" & Mid(strSuffix, 5, 2) & "-" & Mid(strSuffix, 7, 2)) Then
								strNewName = objFolder.Path & "\" & Left(strBaseName, Len(strBaseName) - 9) & "_" & strDate & "." & strExtension
							End If
						End If
					End If
				End If
				If StrComp(objFile.Path, strNewName, vbTextCompare) Then
					strOldPath = objFile.Path
					objFSO.MoveFile strOldPath, strNewName
					WriteOutput Now & ": " & strOldPath & " renamed to " & strNewName
				End If
			Next
		End If
	End If
	WriteOutput Now & ": Script finished"
	objLog.Close
End If

Sub WriteOutput(strMessage)
	WScript.Echo strMessage
	objLog.WriteLine strMessage
End Sub

Open in new window

0
 

Author Comment

by:LD16
ID: 40631648
Hello Rob,

I tried to run your script and here are my remarks:

1-I have an error message (line 35 char 6) file not found.(I re-check folders variable and all is good)

2-The log file just make apears the following line:"2/25/2015 9:29:19 PM: Script started"

3-The file rename has been performed just for files which have a datemodified that contains contains current month (02/2015).

Thank you again for your help.
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 40631703
Oh whoops.  On line 35, it can't find objFile.Path because it doesn't exist after the Move is executed.  I have corrected that.  Can you try again please?
0
 

Author Comment

by:LD16
ID: 40631732
Hello Rob,
Do you have the revised verion of the script?
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 65

Expert Comment

by:RobSampson
ID: 40631769
Sorry, forgot to mention that I updated the original script to correct the error.  You can copy the code from above and try again.

Rob.
0
 

Author Comment

by:LD16
ID: 40631879
Ok, thank you for this revised version.
I tested and I have some remarks:

1-Everything is ok till it got permission refused, I think (quite sure) this is caused because the script trying to rename the LogFile.txt, and writing on it at the same time. (I put the LogFile.txt in the same folder ;-)

2-Is there a way to add an additional loop excluding the logFile of the rename, and an error line "the file cannot be renamed, someone is editing the file additionnally if an error is encountered the script should continue to the next file. After that this script will be a 10/10 without any doubt§
0
 
LVL 65

Accepted Solution

by:
RobSampson earned 500 total points
ID: 40631918
Sure, no problem. Give this revision a try.

Set objFSO = CreateObject("Scripting.FileSystemObject")
strFolder = "C:\Temp\Scripts\Audit"
strLogFile = "C:\Temp\Scripts\LogFile.txt"
If Right(strFolder, 1) <> "\" Then strFolder = strFolder & "\"
If objFSO.FolderExists(Left(strLogFile, InStr(strLogFile, "\"))) = False Then
	WScript.Echo "Log cannot be created.  " & Left(strLogFile, InStr(strLogFile, "\")) & " does not exist."
Else
	Set objLog = objFSO.OpenTextFile(strLogFile, 8, True)
	WriteOutput Now & ": Script started"
	If objFSO.FolderExists(strFolder) = False Then
		WriteOutput strFolder & " does not exist."
	Else
		Set objFolder = objFSO.GetFolder(strFolder)
		If objFolder.Files.Count = 0 Then
			WriteOutput strFolder & " does not contain any files."
		Else
			For Each objFile In objFolder.Files
				If StrComp(objFile.Path, strLogfile, vbTextCompare) <> 0 Then
					dteModifiedDate = CDate(objFile.DateLastModified)
					strDate = Year(dteModifiedDate) & Right("0" & Month(dteModifiedDate), 2) & Right("0" & Day(dteModifiedDate), 2)
					strBaseName = objFSO.GetBaseName(objFile.Path)
					strExtension = objFSO.GetExtensionName(objFile.Path)
					strNewName = objFolder.Path & "\" & strBaseName & "_" & strDate & "." & strExtension
					If Len(strBaseName) > 9 Then
						If InStrRev(strBaseName, "_") = Len(strBaseName) - 8 Then
							strSuffix = Mid(strBaseName, Len(strBaseName) - 7)
							If IsNumeric(strSuffix) Then
								If IsDate(Left(strSuffix, 4) & "-" & Mid(strSuffix, 5, 2) & "-" & Mid(strSuffix, 7, 2)) Then
									strNewName = objFolder.Path & "\" & Left(strBaseName, Len(strBaseName) - 9) & "_" & strDate & "." & strExtension
								End If
							End If
						End If
					End If
					If StrComp(objFile.Path, strNewName, vbTextCompare) <> 0 Then
						strOldPath = objFile.Path
						On Error Resume Next
						objFSO.MoveFile strOldPath, strNewName
						If Err.Number = 0 Then
							WriteOutput Now & ": " & strOldPath & " renamed to " & strNewName
						Else
							WriteOutput Now & ": Unable to rename " & strOldPath & " to " & strNewName & ". Error " & Err.Number & ": " & Err.Description
						End If
						Err.Clear
						On Error GoTo 0
					End If
				End If
			Next
		End If
	End If
	WriteOutput Now & ": Script finished"
	objLog.Close
End If

Sub WriteOutput(strMessage)
	WScript.Echo strMessage
	objLog.WriteLine strMessage
End Sub

Open in new window


Regards,

Rob.
0
 

Author Comment

by:LD16
ID: 40632685
Hello Rob,

I have tested and it works perfectly!
Thank you!
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 40632726
Great! If you ever need help understanding the code, let me know.

Thanks for the grade.

Rob.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Welcome back!  My apologies for taking so long to write part two of this series; it's been a long time coming!  As I promised in Part 1, this article will focus on how to locate those elusive AD properties that you are searching for.  Why is this us…
Welcome, welcome!  If you are new to the series and haven't been following along, please take a brief moment to review the first three installments: Part 1 (http://www.experts-exchange.com/Programming/Languages/Visual_Basic/VB_Script/A_266-VBScri…
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.
In this video I am going to show you how to back up and restore Office 365 mailboxes using CodeTwo Backup for Office 365. Learn more about the tool used in this video here: http://www.codetwo.com/backup-for-office-365/ (http://www.codetwo.com/ba…

910 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

25 Experts available now in Live!

Get 1:1 Help Now