VBScript For Each isn't working - vbscript

I can't get the following function in VBScript to work. I am trying to get all of the files in a folder and loop through them to get the highest numbered file. (file name format is log_XXX.txt) The problem that I am having is that the code never enters my For Each loop. I am new to VBScript, but I don't seem to understand why this won't work.
Function GetFileNumber(folderspec)
Dim fso, f, f1, fc, s, tempHighNum
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(folderspec)
WScript.Echo f.Files.Count : rem prints 3
Set fc = f.Files
WScript.Echo fc.Count : rem prints 3
Set tempHighNum = "000"
For Each f1 in fc
WScript.Echo f1.Size : rem does not print
WScript.Echo f1.Type : rem does not print
WScript.Echo f1.Name : rem does not print
s = Right(f1.name,3)
IF NOT(ISNULL(s)) THEN
IF (s > tempHighNum) THEN
tempHighNum = s
END IF
END IF
Next
GetFileNumber = tempHighNum
End Function

Change this line:
Set tempHighNum = "000"
to the following:
tempHighNum = "000"
You are attempting to set the tempHighNum variable to a string type. Therefore, you should not use the Set keyword. Set is only needed when assigning object types to variables.

I am not sure how your script works so I put this HTML application together for you. It uses a batch file called Dir.Bat located in C:\Batch which makes a file called Data.Txt located in c:\Temp. Then the script takes
over. The script reads the file Data.Txt line by line. As each line is read two split statements are used to separate out the string in the text file's name. After that I collect those strings containing numbers into the variable ListCol as I test for larger and larger numbers. I finally wind up with the largest number which I place in your original variable tempHighNum. I will post the HTA file and the Dir.Bat file. I know I did not write the script as a function using a parameter so if you really need to use a parameter, I will try to help you by changing the HTA file to make it possible to enter the path and file name in a TextBox. That should make it easy to
change and use. I added and changed a thing or two to make it run smoother.
I am not sure how your script works so I put this HTML application together for you. It uses a batch file called Dir.Bat located in C:\Batch which makes a file called Data.Txt located in c:\Temp. Then the script takes
over. The script reads the file Data.Txt line by line. As each line is read two split statements are used to separate out the string in the text file's name. After that I collect those strings containing numbers into the variable ListCol as I test for larger and larger numbers. I finally wind up with the largest number which I place in your original variable tempHighNum. I will post the HTA file and the Dir.Bat file. I know I did not write the script as a function using a parameter so if you really need to use a parameter, I will try to help you by changing the HTA file to make it possible to enter the path and file name in a TextBox. That should make it easy to
change and use. I added and changed a thing or two to make it run smoother.
<HTML><!-- C:\HTML_and_HTA_CODE_EXAMPLES\ATest.Hta -->
<HEAD>
<TITLE>ATest.Hta</TITLE>
<HTA:APPLICATION ID="HTA MyApp"
APPLICATIONNAME="Help4Saul Dolgin"
BORDER ="thick"
BORDERSTYLE ="complex"
CAPTION ="yes"
CONTEXTMENU ="no"
ICON ="http://Your URL/your icon.ico"
INNERBORDER ="yes"
MAXIMIZEBUTTON ="yes"
MINIMIZEBUTTON ="yes"
NAVIGABLE ="no"
SCROLL ="no"
SHOWINTASKBAR ="yes"
SINGLEINSTANCE ="yes"
SYSMENU ="yes"
VERSION ="1.0"
WINDOWSTATE ="Normal"/>
</HEAD>
<style>
.ExBt21 {background:"#E0E0E0";Color:"red";}/* For Exit Button */
.Spn4 {font-family:"arial";font-weight:"bold";Color:"blue"}
.Spn2 {Color:"red"}
.tAr1 {font-family:"arial";font-weight:"bold";Color:"blue"}
</style>
<SCRIPT Language="VBScript">
Sub GetFileNumber
Dim FSO, f, fc, tempHighNum, strLine, objSHO, line
Dim DataArr, Data1Arr, Data2Arr, ListCol
fc=""
ListCol=""
tempHighNum=000
Set objSHO=CreateObject("WScript.Shell")
objSHO.run "C:\Batch\Dir.bat"
Set FSO = CreateObject( "Scripting.FileSystemObject" )
Set f = FSO.OpenTextFile("c:\Temp\Data.Txt", "1")
Do Until f.AtEndOfStream
fc = fc & f.ReadLine & vbLf
Loop
tArea1.innerHTML=fc
Data1Arr = Split(fc,vbLf)
Count=UBound(Data1Arr)
For x=0 To Count
DataArr = Split(Data1Arr(x),".")
If x <= Count-1 Then
Data2Arr = Split(DataArr(0),"_")
ListCol = ListCol & Data2Arr(1) & vbLf
If Data2Arr(1) > tempHighNum Then
tempHighNum = Data2Arr(1)
End If
End If
Next
Span2.innerHTML=tempHighNum
End Sub
Sub ExtBtn:Window.close:End Sub' Exit Script For Window
</SCRIPT>
<BODY bgcolor="#D0D0D0">
<button OnClick="GetFileNumber">Button To Press</button><br/>
<span id="Span1" class="Spn1">The biggest No. is: </span><span id="Span2" class="Spn2"></span><br/><br/>
<span Id="Span3" Class="Spn3">Dir.Bat looks in: </span><span Id="Span4" Class="Spn4">C:\Temp\Log_???.Txt</span><br/>
<textarea Id="tArea1" class="tAr1" rows="10"></textarea><br/><br/>
<input id="ExBtn21" class="ExBt21" type="Button" name="ExitBtn21" OnClick="ExtBtn" value="&nbsp-Exit-&nbsp"/><!-- Exit Button -->
</BODY>
</HTML>
The Dir.Bat file is next:
#Echo Off
Dir/B c:\Temp\Log_???.Txt>c:\Temp\Data.Txt

Related

WMI Query Output to variable [duplicate]

I can't get the following function in VBScript to work. I am trying to get all of the files in a folder and loop through them to get the highest numbered file. (file name format is log_XXX.txt) The problem that I am having is that the code never enters my For Each loop. I am new to VBScript, but I don't seem to understand why this won't work.
Function GetFileNumber(folderspec)
Dim fso, f, f1, fc, s, tempHighNum
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(folderspec)
WScript.Echo f.Files.Count : rem prints 3
Set fc = f.Files
WScript.Echo fc.Count : rem prints 3
Set tempHighNum = "000"
For Each f1 in fc
WScript.Echo f1.Size : rem does not print
WScript.Echo f1.Type : rem does not print
WScript.Echo f1.Name : rem does not print
s = Right(f1.name,3)
IF NOT(ISNULL(s)) THEN
IF (s > tempHighNum) THEN
tempHighNum = s
END IF
END IF
Next
GetFileNumber = tempHighNum
End Function
Change this line:
Set tempHighNum = "000"
to the following:
tempHighNum = "000"
You are attempting to set the tempHighNum variable to a string type. Therefore, you should not use the Set keyword. Set is only needed when assigning object types to variables.
I am not sure how your script works so I put this HTML application together for you. It uses a batch file called Dir.Bat located in C:\Batch which makes a file called Data.Txt located in c:\Temp. Then the script takes
over. The script reads the file Data.Txt line by line. As each line is read two split statements are used to separate out the string in the text file's name. After that I collect those strings containing numbers into the variable ListCol as I test for larger and larger numbers. I finally wind up with the largest number which I place in your original variable tempHighNum. I will post the HTA file and the Dir.Bat file. I know I did not write the script as a function using a parameter so if you really need to use a parameter, I will try to help you by changing the HTA file to make it possible to enter the path and file name in a TextBox. That should make it easy to
change and use. I added and changed a thing or two to make it run smoother.
I am not sure how your script works so I put this HTML application together for you. It uses a batch file called Dir.Bat located in C:\Batch which makes a file called Data.Txt located in c:\Temp. Then the script takes
over. The script reads the file Data.Txt line by line. As each line is read two split statements are used to separate out the string in the text file's name. After that I collect those strings containing numbers into the variable ListCol as I test for larger and larger numbers. I finally wind up with the largest number which I place in your original variable tempHighNum. I will post the HTA file and the Dir.Bat file. I know I did not write the script as a function using a parameter so if you really need to use a parameter, I will try to help you by changing the HTA file to make it possible to enter the path and file name in a TextBox. That should make it easy to
change and use. I added and changed a thing or two to make it run smoother.
<HTML><!-- C:\HTML_and_HTA_CODE_EXAMPLES\ATest.Hta -->
<HEAD>
<TITLE>ATest.Hta</TITLE>
<HTA:APPLICATION ID="HTA MyApp"
APPLICATIONNAME="Help4Saul Dolgin"
BORDER ="thick"
BORDERSTYLE ="complex"
CAPTION ="yes"
CONTEXTMENU ="no"
ICON ="http://Your URL/your icon.ico"
INNERBORDER ="yes"
MAXIMIZEBUTTON ="yes"
MINIMIZEBUTTON ="yes"
NAVIGABLE ="no"
SCROLL ="no"
SHOWINTASKBAR ="yes"
SINGLEINSTANCE ="yes"
SYSMENU ="yes"
VERSION ="1.0"
WINDOWSTATE ="Normal"/>
</HEAD>
<style>
.ExBt21 {background:"#E0E0E0";Color:"red";}/* For Exit Button */
.Spn4 {font-family:"arial";font-weight:"bold";Color:"blue"}
.Spn2 {Color:"red"}
.tAr1 {font-family:"arial";font-weight:"bold";Color:"blue"}
</style>
<SCRIPT Language="VBScript">
Sub GetFileNumber
Dim FSO, f, fc, tempHighNum, strLine, objSHO, line
Dim DataArr, Data1Arr, Data2Arr, ListCol
fc=""
ListCol=""
tempHighNum=000
Set objSHO=CreateObject("WScript.Shell")
objSHO.run "C:\Batch\Dir.bat"
Set FSO = CreateObject( "Scripting.FileSystemObject" )
Set f = FSO.OpenTextFile("c:\Temp\Data.Txt", "1")
Do Until f.AtEndOfStream
fc = fc & f.ReadLine & vbLf
Loop
tArea1.innerHTML=fc
Data1Arr = Split(fc,vbLf)
Count=UBound(Data1Arr)
For x=0 To Count
DataArr = Split(Data1Arr(x),".")
If x <= Count-1 Then
Data2Arr = Split(DataArr(0),"_")
ListCol = ListCol & Data2Arr(1) & vbLf
If Data2Arr(1) > tempHighNum Then
tempHighNum = Data2Arr(1)
End If
End If
Next
Span2.innerHTML=tempHighNum
End Sub
Sub ExtBtn:Window.close:End Sub' Exit Script For Window
</SCRIPT>
<BODY bgcolor="#D0D0D0">
<button OnClick="GetFileNumber">Button To Press</button><br/>
<span id="Span1" class="Spn1">The biggest No. is: </span><span id="Span2" class="Spn2"></span><br/><br/>
<span Id="Span3" Class="Spn3">Dir.Bat looks in: </span><span Id="Span4" Class="Spn4">C:\Temp\Log_???.Txt</span><br/>
<textarea Id="tArea1" class="tAr1" rows="10"></textarea><br/><br/>
<input id="ExBtn21" class="ExBt21" type="Button" name="ExitBtn21" OnClick="ExtBtn" value="&nbsp-Exit-&nbsp"/><!-- Exit Button -->
</BODY>
</HTML>
The Dir.Bat file is next:
#Echo Off
Dir/B c:\Temp\Log_???.Txt>c:\Temp\Data.Txt

vbscript compare string contents (folder directory) of text files and creates the missing folders

I am currently working on a school assignment to compare strings within text files. These text files contains paths of folder directories. If a directory is not found on the other textfile, it will create that directory, else nothing will happen.
diretory1.txt contains directory strings that are:
C:\mcgfiles\avp
C:\mcgfiles\temp
C:\mcgfiles\logs\activity
C:\mcgfiles\logs\program
C:\mcgfiles\logs\status
C:\mcgfiles\generatedhtml
and diretory2.txt, contains the following
C:\mcgfiles
C:\mcgfiles\avp
C:\mcgfiles\temp
C:\mcgfiles\logs
C:\mcgfiles\logs\activity
C:\mcgfiles\logs\program
C:\mcgfiles\logs\status
C:\mcgfiles\generatedhtml
In the case of my textfiles, directories "C:\mcgfiles" and "C:\mcgfiles\logs" will be created on my drive C:\ since they are missing.
Here is the code I used:
Set objFSO = CreateObject("Scripting.FileSystemObject")
Const ForReading = 1
Set objFile1 = objFSO.OpenTextFile("C:\scripts\directory1.txt", ForReading)
strAddresses = objFile1.ReadAll
objFile1.Close
Set objFile2 = objFSO.OpenTextFile("C:\scripts\directory2.txt", ForReading)
Do Until objFile2.AtEndOfStream
strCurrent = objFile2.ReadLine
If InStr(strAddresses, strCurrent) = 0 Then
objFSO.CreateFolder(strCurrent)
End If
Loop
It works fine when I use "C:\mcgfiles\temp" as the missing directory. But it cant differentiate what's missing when I use "C:\mcgfiles" or "C:\mcgfiles\logs". Maybe its because I used InStr function and it considers "C:\mcgfiles" and "C:\mcgfiles\logs" not missing since it can also be found in "C:\mcgfiles\logs\activity" etc.
I tried to use strComp but still nothing happens. Please help. Thank you
InStr() "returns the position of the first occurrence of one string within another". So "C:\mcgfiles" is found in "C:\mcgfiles\logs". If all of the pathes in the string you search in are terminated by an EOL marker (eg.g vbCrLf) you can use target & EOL as the needle:
>> haystack = "c:\a\b;c:\a;"
>> eol = ";"
>> needle = "c:\a" & eol
>> WScript.Echo InStr(haystack, needle)
>>
8
Other techniques - e.g. using a dictionary of the pathes - are possible, but would need more work.

VBS Readline - using instr(), to match data whilst ignoring extra spaces

I'm trying to find a way to enhance the reliability of my script. It already works but can be thrown off with a simple extra space in the imported text file.
So I'd like to change my script to Readline if I can find a way to do something like:
Example of text in the .txt file:
FLIGHTS OVER TUSKY PLEASE FILE:
AT OR WEST OF A LINE RBV..LLUND..BAYYS..PUT..DIRECT
FLIGHTS OVER EBONY PLEASE FILE:
AT OR WEST OF A LINE RBV..LLUND..BAYYS..PUT..DIRECT
I know the following doesn't work but if there was a simple modification this would be good.
set WshShell = WScript.CreateObject("WScript.Shell")
Return = WshShell.Run("C:\Downloads\software\putty.exe -load "testing")
set objFSO = CreateObject("Scripting.FileSystemObject")
set objFile = objFSO.OpenTextFile("C:\Users\AW\Desktop\Entries1.txt")
strLine = objFile.ReadAll
If InStr(strLine1, "OVER TUSKY PLEASE") and InStr(strLine2, "BAYYS..PUT..DIRECT") Then
trans307="TUSKY"
ind306="4"
WHAT I'M USING NOW:
I edit the text file in notepad++ to FIND & REPLACE "\n" with "" and "\r" with " " and then it's all one text string and I search for strings within that string.
If InStr(strLine, "FLIGHTS OVER TUSKY PLEASE FILE: AT OR WEST OF A LINE ..RBV..LLUND..BAYYS..PUT..DIRECT") _
or InStr(strLine, "FLIGHTS OVER TUSKY PLEASE FILE: AT OR WEST OF A LINE RBV..LLUND..BAYYS..PUT...DIRECT") Then
trans308C="TUSKY"
ind308C="4"
Problem: If the creators of the text file put another space " " anywhere in this line "AT OR WEST OF A LINE RBV..LLUND..BAYYS..PUT..DIRECT" the script will not identify the string. In the above example I have had to create another or InStr(strLine, "") statement with an extra space or with a couple of dots.
UPDATE:
I will try something like:
set objFSO = CreateObject("Scripting.FileSystemObject")
set objFile = objFSO.OpenTextFile("C:\Users\AW\Desktop\Entries1.txt")
strLine1 = objFile.Readline(1)
strLine2 = objFile.Readline(2)
If InStr(strLine1, "FLIGHTS OVER TUSKY") and InStr(strLine2, "RBV..LLUND..BAYYS..PUT..DIRECT") Then
trans1="TUSKY"
ind1="4"
and see if I can get that to read 2 lines at a time, and loop through the text file.
If you're scared of regex and looking for an alternative, you could create a clunky function to add to your script. Based on your samples, it would seem that fullstops are also never normally used for normal purposes and tend to represent spaces. (I would recommend using Regex instead!)
Using these presumptions, you could create a clunky function like this, that looks for fullstops, and converts them to spaces, removing extra spaces.. Obviously, this relies heavily on your input source files not changing too much - you really should be using a regex to work this stuff out properly.
You could test for the basic expected results using something like the function below.
For example say you had a line of text set in firLine with multiple spaces or fullstops, the function would recognize this:
firLine = "THIS.IS.A.TEST..YOU...SEE MULTIPLE SPACES"
if instr(sanitize(firLine),"THIS IS A TEST YOU SEE MULTIPLE SPACES") then
wscript.echo "Found it"
End If
Here's the clunky function that you could just paste at the end of your script:
Function sanitize(srStr)
Dim preSanitize, srC, spaceMarker
preSanitize = ""
for srC = 1 to len(srStr)
if mid(srStr, srC, 1) = "." then
preSanitize = preSanitize & " "
else
preSanitize = preSanitize & mid(srStr, srC, 1)
End If
spaceMarker = false
sanitize = ""
for srC = 1 to len(preSanitize)
If mid(preSanitize, srC, 1) = " " then
if spaceMarker = false then
sanitize = sanitize & mid(preSanitize, srC, 1)
spaceMarker = true
End If
else
sanitize = sanitize & mid(preSanitize, srC, 1)
spaceMarker = false
End If
Next
End Function
InStr() is a good tool for checking whether a strings contains a fixed/literal string or not. To allow for variation, you should use Regular Expressions (see this or that).
First of all, however, you should work on your specs. Describe in plain words and with some samples what you consider (not) to be a match.
E.g.: A string containing the words "FLIGHTS", "OVER", and "TUSKY" in that order with at least one space in between is a match - "FLIGHTS OVER TUSKY", "FLIGHTS OVER TUSKY"; "FLIGHTS OVER TUSKANY" is a 'near miss' - what about "AIRFLIGHTS OVER TUSKY"?
GREAT NEWS! I finally figured out how to do this.
Here is a snippet from "Entries1.txt"
FLIGHTS OVER BRADD KANNI PLEASE FILE:
VIA J174.RIFLE..ACK..DIRECT
OR RBV.J62.ACK..DIRECT
FLIGHTS OVER KANNI WHALE PLEASE FILE:
VIA J174.RIFLE..ACK..DIRECT OR
FLIGHTS OVER WHALE PLEASE FILE:"
ETC, ETC
set WshShell = WScript.CreateObject("WScript.Shell")
set objFSO = CreateObject("Scripting.FileSystemObject")
set objFile = objFSO.OpenTextFile("C:\Users\AW\Desktop\Entries1.txt")
Do until objFile.AtEndOfStream
firLine = objFile.ReadLine
If InStr(firLine, "FLIGHTS OVER KANNI WHALE PLEASE") Then
secLine = objFile.ReadLine
If InStr(secLine, "J174.RIFLE..ACK..DIRECT") Then
'I'm going to change the below once I piece it all together.
WScript.Echo "works"
Else WScript.Echo "Not found"
'cut, paste and modify all my "IF" statements below
End If
End If
loop

Trouble copying text file into Excel using VBA

I want to copy contents from text file to an Excel cell using VBA. I can do this succesfully from most text files. But in case of certain files, the code is copying only partial data into the excel file.
This is the code I used for copying
FileName = folderpath & sFile
Set mytextfile = Workbooks.Open(FileName)
mytextfile.Sheets(1).Cells.CurrentRegion.Copy ThisWorkbook.Sheets("RawData").Range("A" & inputRow)
'mytextfile.Sheets(1).Range("A1").CurrentRegion.Copy ThisWorkbook.Sheets("RawData").Range("A" & inputRow)
mytextfile.Close (False)
I already understand what is the problem. While opening certain text files as excel files, some contents are present in cell A1 and the rest in cell A2.
I don't know why it is opened so. I am posting contents of two text file below:
1)Text file whose contents are contained in different cells when opened in excel
fwi!3F5A!041!g1ksIpqub7J MCMILLAN J. PIIKKILA RAYMONDBERRY#WEBTV.NET
+001 061 477 130 F g3ktHqrwc9 CLE!g1ksIpqub7 CLEHS04C |P.O. BOX 171 SEARSPORT,ME Nashville 68800 AZ| |5150 CTY RD 525 Raleigh 64292|
18000000 0412CL0 1 N 2
I got the following output when I used the above text file.
fwi!3F5A!041!g1ksIpqub7J MCMILLAN J. PIIKKILA RAYMONDBERRY#WEBTV.NET +001 061 477 130 F g3ktHqrwc9 CLE!g1ksIpqub7 CLEHS04C |P.O. BOX 171 SEARSPORT
2)Text file whose contents are contained in a single cell A1
fSj!3U68!071!gQloo3d5OGG Presley Y. TART JR PULPACTION82#HOIMAIL.COM
+001 047 475273 M gQmqq6d8ME CVE!gQloo3d5OG CVEGF07C |10001 SW 125TH CT RD Reno 88595 TN| |10849 DEBORAH DRIVE Glendale 70958| 97400000
0712CV0 0 N 0
I got the following output when I used the above text file.
fSj!3U68!071!gQloo3d5OGG Presley Y. TART JR PULPACTION82#HOIMAIL.COM +001 047 475273 M gQmqq6d8ME CVE!gQloo3d5OG CVEGF07C |10001 SW 125TH CT RD Reno 88595 TN| |10849 DEBORAH DRIVE Glendale 70958| 97400000 0712CV0 0 N 0
There is no apparent difference between the contents of these two file.
I also tried this code but without any success:
FileName = folderpath & sFile
Set mytextfile = Workbooks.Open(FileName)
mytextfile.Sheets(1).Range("A1").CurrentRegion.Copy ThisWorkbook.Sheets("RawData").Range("A" & inputRow)
mytextfile.Close (False)
Problem:
You are not using the right approach to read a *.txt file in VBA. Opening file using Workbooks.Open() treats the opened file as a *.csv. Therefore, when Excel is reading a stream and a comma occurs it treats it as a new line separator and throws the remaining part (after the comma) to the next cell. As stated on MSDN Workbooks.Open Method
expression .Open(FileName ... )
expression A variable that represents a Workbooks object.
Clearly, a Workbook object not a txt file.
Solution:
The right approach to read content of a *.txt file is to use the FileSystemObject and TextStream objects from the Microsoft Scripting Runtime Library.
I wrote a simple Sub for you that reads the entire content of a *.txt file. In order to make it work you have to add references to your project
In VBE window, click Tools » References » scroll down, find, and tick Microsoft Scripting Runtime
Now, screen through the below code and modify the path to your *.txt file or pass the path through a parameter and the entire content of your *.txt file will be placed in the first Sheet Sheet(1) Cell A1
Sub ReadTxtFile()
Dim oFSO As New FileSystemObject
Dim oFS As TextStream
Dim fileName As String
' make sure to update your path or
' pass it to the sub through parameter
fileName = "C:\Users\fooboo\Desktop\text.txt"
Set oFS = oFSO.OpenTextFile(fileName)
Dim content As String
content = oFS.ReadAll
With Sheets(1).Range("A1")
.ClearContents
.NumberFormat = "#"
.Value = content
End With
oFS.Close
Set oFS = Nothing
Set oFSO = Nothing
End Sub

Renaming pdf files with a batch file

I need to either write a batch file or a vbscript that will rename files. I need to keep everything in the file name up to the second "." but delete what comes after the second dot.
This is a sample of what the file names look like:
nnnnnnnnnnnnnnnn.xxxxxxxx.dddddddddd.pdf
n= 16 numbers 0-9
x= date in this format ex:02232008
d= 10 numbers 0-9, this is the part of the file name that I want to delete.
I need the d's from the sample above to be deleted but keep the rest of the file name the same. I need to be able to run this batch file on a folder that contains about 3,000 pdf files. It can either be put right back into the same folder or outputted into a different folder.
FOR /F "USEBACKQ delims=. tokens=1-4" %%F IN (`DIR /B /A-D "C:\Path\To\PDFs\"`) DO (
REN "%%~fF.%%G.%%H.%%I" "%%F.%%G.%%I"
)
If you have files that vary in how many periods there are, just need to add a simple argument to count how many period delimiters exist then execute.
In VBScript, you can use something like
' the file paths. hardcoded, but you could alternatively collect these via command line parameters
Const IN_PATH = "path\to\directory"
Const OUT_PATH = "path\to\another\directory"
' check that the directories exist. you could create them instead, but here
' it just throws an error as that's easier
dim fso: set fso = CreateObject("Scripting.FileSystemObject")
if not fso.FolderExists(IN_PATH) then
err.raise 1,, "Path '" & IN_PATH & "' not found"
end if
if not fso.FolderExists(OUT_PATH) then
err.raise 1,, "Path '" & OUT_PATH & "' not found"
end if
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, ".")
' we're expecting a file format of a.b.c.pdf
' so we should have 4 elements in the array (zero-indexed, highest bound is 3)
if UBound(parts) = 3 then
' rebuild the name with the 0th, 1st and 3rd elements
dim newname: newname = parts(0) & "." & parts(1) & "." & parts(3)
' use the move() method to effect the rename
file.move fso.buildpath(OUT_PATH, newname)
else
' log the fact that there's an erroneous file name
WScript.Echo "Unexpected file format: '" & name & "'"
end if
next 'file
You would run it in a batch file thus, redirecting output to a log file
cscript rename-script.vbs > logfile.txt
This assumes that you can simply rely on the period to delimit the parts of the file name rather than the specifics of the format of the delimited parts.
To rearrange the date, which I think is in the parts(1) array element, you can simply extract each bit of the string because it's in a specific format:
'date in format mmddyyyy
dim month_, day_, year_, date_
month_ = left(parts(1), 2)
day_ = mid(parts(1), 3, 2)
year_ = right(parts(1), 4)
date_ = year_ & month_ & day_ ' now yyyymmdd
so when rebuilding the filename, you can replace parts(1) with the new formatted date
dim newname: newname = parts(0) & "." & date_ & "." & parts(3)
Using StringSolver, a semi-automatic renaming tool, just rename the first file, check that the generalized renaming is ok, and then accept it on all other files.
> move 1234567890123456.02232008.1946738250.pdf 1234567890123456.02232008.pdf
Get the explanation:
> move --explain
the file name until the end of the second number + the extension
If you are satisfied, you can run the semi-automated tool using move --auto or the succint version:
> move
DISCLAIMER: I am a co-author of this free software made for academic purposes.

Resources