Renaming multiple files in a loop - vbscript

I have a folder with 8 Excel files with the following naming convention:
date_All_Groups
date_HRFull_Status_All
date_RME_Groups_Excluded
These files are used for monthly reports, therefore the date will obviously always be different.
I will be using a macro to manipulate the data in each worksheet, however I cannot create the macro due the changing file name (the date) - the only guarantee I have is that each of these files will DEFINITELY contain a partial string match.
I have a script that finds the files in the location and will rename the file, but it only renames 1 file and its not the first file in the folder.
My issue is using the For Each loop effectively.
Here's the code I have:
Dim fso, folder, file
Dim folderName, searchFileName, renameFile1, renameFile2, renameFile3, renameFile4, renameFile5, renameFile6, renameFile7, renameFile8
'Path
folderName = "C:\test\"
'Future FileName
renameFile1 = "All Groups.csv"
renameFile2 = "Groups Excluded.csv"
renameFile3 = "No Exclusions.csv"
renameFile4 = "HR.csv"
renameFile5 = "AD Users.csv"
renameFile6 = "Encryption Status.csv"
renameFile7 = "ePO4 Not Encrypted.csv"
renameFile8 = "ePO5 Not Encrypted.csv"
' Create filesystem object and the folder object
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder(folderName)
' Loop over all files in the folder until the searchFileName is found
For Each file In folder.Files
' See If the file starts with the name we search
If InStr(file.Name, "All_Groups") then
file.Name = renameFile1
End If
If InStr(file.Name, "Groups_Excluded") Then
file.Name = renameFile2
End If
If InStr(file.Name, "No_Exclusions") Then
file.Name = renameFile3
End If
If InStr(file.Name, "HR") Then
file.Name = renameFile4
End If
If InStr(file.Name, "AD_Users") then
file.Name = renameFile5
End If
If InStr(file.Name, "Encryption_Status") then
file.Name = renameFile6
End If
If InStr(file.Name, "ePO4") then
file.Name = renameFile7
End If
If InStr(file.Name, "ePO5") then
file.Name = renameFile8
End If
Exit For
' echo the job is completed
WScript.Echo "Completed!"
Next
The original code I found was exactly as above, but with only one If statement inside the For Each loop and the Exit For was inside the If statement.
Currently when I execute the script, the code renames only one file and its always the HR file first.
If I execute the script again, it then starts with All Groups, then Groups Excluded, and so on.
And the "Echo Completed" does not do anything either.

If you just want to rename your files to "canonical" names you could do something like this, assuming that you just want the date from the beginning of the filename removed and the underscores replaced with spaces:
Set re = New RegExp
re.Pattern = "\d{4}-\d{2}-\d{2}_(.*\.csv)"
For Each f In folder.Files
For Each m In re.Execute(f.Name)
f.Name = Replace(m.Submatches(0), "_", " ")
Next
Next

If the files have the same "date" you only need Find for that, for excample (if the date is a iso date "YYYYMMDD") (Date Returns "today" date)
IsoDate=CStr(Year(Date)) & Right("0" & CStr(Month(Date)),2) & Right("0" & CStr(Day(Date)),2)
And the for each:
For Each file In folder.Files
If InStr(file.Name, IsoDate) = 1 then 'if is in the start of the string
file.Name = Mid(file.Name, Len(IsoDate)+1) 'The same name with out date
End IF
Next

Related

Rename part of file

I require a VBScript that finds the most recent file in a folder and renames it. I have been able to write the script so that it finds the most recent file. However, I cannot figure out how to correctly have the file renamed once identified. I have been able to rename the file with a basic name, confirming the script works.
The file name needs the letter "A" added in the middle.
The file will already be saved as 20160229_TITLES and it needs to become 20160229A_TITLES.
Below is a script I tried to just pull the year and add the "A". I figured if I could get the year to add to the beginning, I could then add in the month and year. The date will always be the current date. This continues to cause an error message.
Option Explicit
Dim fso, folder, file, Date, recentFile
Dim folderName, searchFileName, renameFileTo
folderName = "C:\Ticket\Test\"
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder(folderName)
Set recentFile = Nothing
For Each file In folder.Files
If (recentFile is Nothing) Then
Set recentFile = file
ElseIf FormatDateTime(file.DateLastModified) = Date Then
Set recentFile = file
End If
Next
recentFile.Name = Replace(recentFile.Name, "_", "A_")
Assuming that the filename will always consist of a date followed by an underscore and some other text you could do several things:
replace underscores with "A_" (if there is only one underscore in the name):
file.Name = Replace(file.Name, "_", "A_")
split the name at the first underscore, append "A" to the first fragment and join the fragments back together:
arr = Split(file.Name, "_", 2)
arr(0) = arr(0) & "A"
file.Name = Join(arr, "_")
do a regular expression replacement:
Set re = New RegExp
re.Pattern = "^(\d{8})_"
file.Name = re.Replace(file.Name, "$1A_")
The answer #Ansgar provided helped me correctly rename the file, however, I learned that the script only searched for any file that was newer than any other file and renamed it. The following script correctly renames the file that was modified today. Thank you for all your help #Ansgar. :)
Option Explicit
Dim fso, folder, file, todaysDate, recentFile
Dim folderName, searchFileName, renameFileTo
folderName = "C:\Ticket\Test\"
todaysDate = Date()
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder(folderName)
set recentFile = Nothing
For each file In folder.Files
If (recentFile is Nothing) Then
Set recentFile = file
ElseIf DateValue (file.DateLastModified) = todaysDate then
Set recentFile = file
Exit For
End IF
Next
recentFile.Name = Replace(recentFile.Name, "_", "A_")

how do i get all .csv files from a folder for the present day using vbscript

Scan folder and list only .csv files which are created on that particular day.
option explicit
dim fileSystem, folder, file, path, myDate
path = "C:\vbs"
Set fileSystem = CreateObject("Scripting.FileSystemObject")
myDate = dateadd("d", -1, FormatDateTime(Now, 2))
Set folder = fileSystem.GetFolder(path)
for each file in folder.Files
if file.DateCreated > myDate then
WScript.Echo file.Name & " created at " & file.DateCreated
If UCase(filesystem.GetExtensionName(objFile.name)) = "csv" then
Wscript.Echo objFile.Name
End If
End If
next
Your
If UCase(filesystem.GetExtensionName(objFile.name)) = "csv" then
transforms the extension to uppercase, but then compares it to a lowercase "csv".
DateAdd's third parameter should be a date; Now (a date) shouldn't be converted to a string.

Read files in subfolders

I'm trying to make a script that we can output a specific string ino a files from a list of files in different subfolders.
My script works but onl for one directory. I need some help to make it works with subfolders
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set folder = objFSO.GetFolder("D:\vbs\logs\") ' here i have loads of subfolders with *.txt
Set outfile = objFSO.CreateTextFile("D:\vbs\ok\test.txt") ' my output file
for each file in folder.Files
Set testfile = objFSO.OpenTextFile(file.path, ForReading)
Do While Not testfile.AtEndOfStream
If instr (testfile.readline, "central") then ' i output every lines where there is the word "central"
outfile.writeline testfile.readline
End If
if instr (testfile.readline, "version") then ' i use this to parse my output file to get a indication between every files read
num = testfile.readline
mag = Split(num)
elseif testfile.AtEndOfStream = true then
outfile.writeline "Shop " & mag(4)
end if
Loop
testfile.close
next
outfile.close
See this answer to a similar question for a folder recursion example.
One remark about your existing code, though: each call of the ReadLine method reads the next line from the file, so something like this:
If instr (testfile.readline, "central") then
outfile.writeline testfile.readline
End If
will not output the line containing the word "central" (as your comments say), but the line after that line.
If you want to output the line containing the word you're checking for, you have to store the read line in a variable and continue with that variable:
line = testfile.ReadLine
If InStr(line, "central") Then
outfile.WriteLine line
End If
I would encapsulate your entire For...Each block into a new subroutine and then add a new For...Each block to capture all subFolders in the parent folder. I added that functionality to your script, see below.
Const ForReading = 1
Const Start_Folder = "D:\vbs\logs\" ' here i have loads of subfolders with *.txt
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set outfile = objFSO.CreateTextFile("D:\vbs\ok\test.txt") ' my output file
'Call the Search subroutine to start the recursive search.
Search objFSO.GetFolder(Start_Folder)
'Close the outfile after all folders have been searched
outfile.Close
Sub Search(sDir)
for each file in sDir.Files
Set testfile = objFSO.OpenTextFile(file.path, ForReading)
Do While Not testfile.AtEndOfStream
If instr (testfile.readline, "central") then ' i output every lines where there is the word "central"
outfile.writeline testfile.readline
End If
if instr (testfile.readline, "version") then ' i use this to parse my output file to get a indication between every files read
num = testfile.readline
mag = Split(num)
elseif testfile.AtEndOfStream = true then
outfile.writeline "Shop " & mag(4)
end if
Loop
testfile.close
next
'Find EACH SUBFOLDER.
For Each subFolder In sDir.SubFolders
'Call the Search subroutine to start the recursive search on EACH SUBFOLDER.
Search objFSO.GetFolder(subFolder.Path)
Next
End Sub

How can I exclude .txt files from being renamed?

The code below does 2 things, looks at all the files in a particular, determines if the files have .pdf extension. If any file doesn't, it fixes the extension and then moves all the files to another folder.
So far, this script does all of that great.
Problem is that 3 files with .txt extensions are always included with this list and we don't want the extensions for these files changed and we don't want them moved either.
The files are called index.txt, pending.txt and tableofcontents.txt.
Is this possible?
Here is the code I have so far and thanks a lot in advance.
Set FSO = CreateObject("Scripting.FileSystemObject")
Set pdfFolder = FSO.GetFolder( "E:\LOCS\FTP\Current\")
For Each fil In pdfFolder.Files
' check each file to be sure it fits the pattern
fname = fil.Name
suffix = LCase( Right( fname, 4 ) )
'prefix = Left( fname, 8 )
' so suffix has to be right:
If suffix = ".pdf" Then
newName = Mid( fname, 9 )
' Response.Write "Renaming '" & fname & "' to '" & newName & "'<br/>" & vbNewLine
fil.Move "E:\DOCs\PermLoc\" & newName
End If
Next
Try setting a breakpoint and stepping through the code to see what suffixes are being compared and if ".txt" = ".pdf" is returning true and entering the If statement.

If file exists then delete the file

I have a vbscript that is used to rename files. What I need to implement into the script is something that deletes the "new file" if it already exists.
For example: I have a batch of files that are named like this 11111111.dddddddd.pdf where the files get renamed to 11111111.pdf. The problem is that when I rename to the 11111111.pdf format I end of with files that are duplicated and then makes the script fail because you obviously cant have 2 files with the same name. I need it to rename the first one but then delete the others that are renamed the same.
Here is what I have so far for my IF statement but it doesnt work and I get and error that says "Type mismatch: 'FileExists". I am not sure how to get this part of the code to execute the way I would like. Any help or suggestions would be greatly appreciated.
dim infolder: set infolder = fso.GetFolder(IN_PATH)
dim file
for each file in infolder.files
dim name: name = file.name
dim parts: parts = split(name, ".")
dim acct_, date_
acct_ = parts(0)
date_ = parts(1)
' file format of a.c.pdf
if UBound(parts) = 2 then
' rebuild the name with the 0th and 2nd elements
dim newname: newname = acct_ & "." & parts(2)
' use the move() method to effect the rename
file.move fso.buildpath(OUT_PATH, newname)
if newname = FileExists(file.name) Then
newname.DeleteFile()
end if
end if
next 'file
You're close, you just need to delete the file before trying to over-write it.
dim infolder: set infolder = fso.GetFolder(IN_PATH)
dim file: for each file in infolder.Files
dim name: name = file.name
dim parts: parts = split(name, ".")
if UBound(parts) = 2 then
' file name like a.c.pdf
dim newname: newname = parts(0) & "." & parts(2)
dim newpath: newpath = fso.BuildPath(OUT_PATH, newname)
' warning:
' if we have source files C:\IN_PATH\ABC.01.PDF, C:\IN_PATH\ABC.02.PDF, ...
' only one of them will be saved as D:\OUT_PATH\ABC.PDF
if fso.FileExists(newpath) then
fso.DeleteFile newpath
end if
file.Move newpath
end if
next
fileExists() is a method of FileSystemObject, not a global scope function.
You also have an issue with the delete, DeleteFile() is also a method of FileSystemObject.
Furthermore, it seems you are moving the file and then attempting to deal with the overwrite issue, which is out of order. First you must detect the name collision, so you can choose the rename the file or delete the collision first. I am assuming for some reason you want to keep deleting the new files until you get to the last one, which seemed implied in your question.
So you could use the block:
if NOT fso.FileExists(newname) Then
file.move fso.buildpath(OUT_PATH, newname)
else
fso.DeleteFile newname
file.move fso.buildpath(OUT_PATH, newname)
end if
Also be careful that your string comparison with the = sign is case sensitive. Use strCmp with vbText compare option for case insensitive string comparison.
IF both POS_History_bim_data_*.zip and POS_History_bim_data_*.zip.trg exists in Y:\ExternalData\RSIDest\ Folder then Delete File Y:\ExternalData\RSIDest\Target_slpos_unzip_done.dat

Resources