Read data from ini file - vbscript

i have a vbscript that takes input file name
the code is
Dim tsout: Set tsout = gofs.CreateTextFile("C:\....csv")
Dim tsin: Set tsin = gofs.OpenTextFile("C:\.....csv")
how can i configure this so that path createTextFile(....) is read from config file(.ini)
the file path for creating and writing output-to, must be taken from ini file
this is my ini file
// my ini file
[Read_file]
tsout=E:.....tt.csv
tsin=E:\....gt.csv
[col]
Number1=4
Number2=5

A simple version of an .ini file parser:
Option Explicit
Dim goFS : Set goFS = CreateObject("Scripting.FileSystemObject")
'WScript.Quit demoReadFile()
WScript.Quit demoReadIniFile()
Function demoReadFile()
demoReadFile = 0
Dim tsIn : Set tsIn = goFS.OpenTextFile(".\21825192.ini")
Do Until tsIn.AtEndOfStream
Dim sLine : sLine = tsIn.ReadLine()
WScript.Echo tsIn.Line - 1, sLine
Loop
tsIn.Close
End Function
Function demoReadIniFile()
demoReadIniFile = 0
Dim dicIni : Set dicIni = ReadIniFile(".\21825192.ini")
Dim sSec, sKV
For Each sSec In dicIni.Keys()
WScript.Echo "---", sSec
For Each sKV In dicIni(sSec).Keys()
WScript.Echo " ", sKV, "=>", dicIni(sSec)(sKV)
Next
Next
WScript.Echo dicIni("tsout")("Path")
End Function
Function ReadIniFile(sFSpec)
Dim dicTmp : Set dicTmp = CreateObject("Scripting.Dictionary")
Dim tsIn : Set tsIn = goFS.OpenTextFile(sFSpec)
Dim sLine, sSec, aKV
Do Until tsIn.AtEndOfStream
sLine = Trim(tsIn.ReadLine())
If "[" = Left(sLine, 1) Then
sSec = Mid(sLine, 2, Len(sLine) - 2)
Set dicTmp(sSEc) = CreateObject("Scripting.Dictionary")
Else
If "" <> sLine Then
aKV = Split(sLine, "=")
If 1 = UBound(aKV) Then
dicTmp(sSec)(Trim(aKV(0))) = Trim(aKV(1))
End If
End If
End If
Loop
tsIn.Close
Set ReadIniFile = dicTmp
End Function
output:
cscript 21825192.vbs
1 [pipapo]
2 Path=E:\dont\find\me.csv
3 Some = thing else
4
5 [tsout]
6 Path=E:\where\ever\output.csv
7 abc=def
cscript 21825192.vbs
--- pipapo
Path => E:\dont\find\me.csv
Some => thing else
--- tsout
Path => E:\where\ever\output.csv
abc => def
E:\where\ever\output.csv
(see this answer for background)
Update wrt comment/edit:
I added your sections to my sample .ini file:
type 21825192.ini
[pipapo]
Path=E:\dont\find\me.csv
Some = thing else
[tsout]
Path=E:\where\ever\output.csv
abc=def
[Read_file]
tsout=E:.....tt.csv
tsin=E:\....gt.csv
[col]
Number1=4
Number2=5
and - just for clarity - changed the final output line of my demoReadIniFile() function to:
WScript.Echo "tsout.Path", dicIni("tsout")("Path")
WScript.Echo "Read_file.tsin", dicIni("Read_file")("tsin")
WScript.Echo "col.Number2", dicIni("col")("Number2")
The output:
cscript 21825192.vbs
--- pipapo
Path => E:\dont\find\me.csv
Some => thing else
--- tsout
Path => E:\where\ever\output.csv
abc => def
--- Read_file
tsout => E:.....tt.csv
tsin => E:\....gt.csv
--- col
Number1 => 4
Number2 => 5
tsout.Path E:\where\ever\output.csv
Read_file.tsin E:\....gt.csv
col.Number2 5
So I don't understand at all why accessing 'the col section taking out number1=4 and Number2=5' causes any problems.

VBS do not support IniFile class. You need to create own parser of INI file. Other solution (also with creating own parsing functions, but much easy than to parse INI file): save TAB delimited data, for example: first comming OUTgoing file, than TAB char, than INcomming file.

Ekkehard's demo tweaked for Classic ASP:
Function demoReadIniFile()
demoReadIniFile = 0
Dim dicIni : Set dicIni = ReadIniFile("c:\path\to\21825192.ini")
Dim sSec, sKV
For Each sSec In dicIni.Keys()
response.write "---" & sSec & "<br>"
For Each sKV In dicIni(sSec).Keys()
response.write " " & sKV & " => " & dicIni(sSec)(sKV) & "<br>"
Next
Next
' response.write dicIni("tsout")("Path") & "<br>"
End Function
His ReadIniFile() works as written.

Related

Edit a CSV Record

How do I edit a record in a CSV file?
for example I have a .csv file named "test.csv" and inside it is:
"123","Active"
"456","Not-Active"
"999000123","Active"
How can I edit "456" and change it from Not-Active to Active
The only way I can think of it is to:
Open the .csv file. Maybe store the data inside a string?
Search for "456",".
Get the line position of "456",". How to do this?
Delete the line that we just got the position of. How to do this?
Recreate the line with what we want. How to do this?
Insert the recreated data in the line position. How to do this?
Save the .csv file.
But is there not a easier way to do this?
And if not how do I do steps # 4, 5, and 6?
Maybe to convert it onto an Array or something? But I have no idea how to do this in Classic ASP.
Based on Ekkehards answer, here is the ASP version. The .csv file needs to be located in the same directory as the .asp script. Feel free to award the points to Ekkehard
<%#LANGUAGE="VBSCRIPT"%>
<% option explicit %>
<%
Dim goFS : Set goFS = CreateObject("Scripting.FileSystemObject")
Dim tsIn : Set tsIn = goFS.OpenTextFile(Server.MapPath( "46734115.csv"))
Dim tsOut : Set tsOut = goFS.CreateTextFile(Server.MapPath("46734115-2.csv"))
Dim sLine
Do Until tsIn.AtEndOfStream
sLine = tsIn.ReadLine()
dim pos : pos = instr( sLine, """456"",")
Response.Write(pos)
if pos > 0 then
' to keep things simple, just replace the whole line
sLine = """456"",""Active"""
end if
tsOut.WriteLine sLine
' Just so there is something to see: print line to the browser window
Response.Write( sLine & "<br />")
Loop
tsOut.Close
tsIn.Close
%>
A simplyfied version of the script #abr mentioned:
Dim goFS : Set goFS = CreateObject("Scripting.FileSystemObject")
Dim tsIn : Set tsIn = goFS.OpenTextFile("..\data\46734115.csv")
Dim tsOut : Set tsOut = goFS.CreateTextFile("..\data\46734115-2.csv")
Dim sLine
Do Until tsIn.AtEndOfStream
sLine = tsIn.ReadLine()
WScript.Echo "<", sLine
If "456," = Left(sLine, 4) Then
sLine = "789,""something else"""
End If
WScript.Echo ">", sLine
tsOut.WriteLine sLine
WScript.Echo
Loop
tsOut.Close
tsIn.Close
output:
type ..\data\46734115.csv
123,"Active"
456,"Not-Active"
999000123,"Active"
cscript 46734115-3.vbs
< 123,"Active"
> 123,"Active"
< 456,"Not-Active"
> 789,"something else"
< 999000123,"Active"
> 999000123,"Active"
type ..\data\46734115-2.csv
123,"Active"
789,"something else"
999000123,"Active"

read folder path and using the path to access the files and rename it

I want to write a VBScript that can access a config file which has the folder path. Once directed to the folder, there are documents with _DDMMYYYY. I want to remove the _ and the date stamp.
Can somebody help me please?
Option Explicit
Dim FSO: Set FSO = CreateObject("Scripting.FileSystemObject")
'Declare the variables to be used from the property file
Dim Folder
Dim objWMIService, objProcess, colProcess, obNetwork
Dim strComputer, WshShell, strComputerName
strComputer = "."
Set obNetwork = WScript.CreateObject("Wscript.Network")
strComputerName = obNetwork.ComputerName
Set obNetwork = Nothing
SetConfigFromFile("C:\Users\Lenovo\Desktop\RenameFile\ConfigPad.txt")
MsgBox "Folder = " & Folder
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run Folder
'---------- Get Variables from ConfigPad.txt ----------
Sub SetConfigFromFile(fileName)
Dim strConfigLine
Dim fConFile
Dim EqualSignPosition
Dim strLen
Dim VariableName
Dim VariableValue
Set fConFile = fso.OpenTextFile(fileName)
While Not fConFile.AtEndOfStream
strConfigLine = fConFile.ReadLine
strConfigLine = Trim(strConfigLine)
'MsgBox(strConfigLine)
If (InStr(1,strConfigLine,"#",1) <> 1 And Len(strConfigLine) <> 0) Then
EqualSignPosition = InStr(1, strConfigLine, "=", 1)
strLen = Len(strConfigLine)
VariableName = LCase(Trim(MID(strConfigLine, 1, EqualSignPosition-1))) 'line 34
VariableValue = Trim(Mid(strConfigLine, EqualSignPosition + 1, strLen - EqualSignPosition))
Select Case VariableName
'ADD EACH OCCURRENCE OF THE CONFIGURATION FILE VARIABLES(KEYS)
Case LCase("Folder")
If VariableValue <> "" Then Folder = VariableValue
End Select
End If
Wend
fConFile.Close
End Sub
'---------- Rename the documents ----------
Dim FLD
Dim fil
Dim strOldName
Dim strNewName
Dim strFileParts
'Set the folder you want to search.
Set FLD = FSO.GetFolder("C:\Users\Lenovo\Desktop\RenameFile\RenameFile.vbs")
'Loop through each file in the folder
For Each fil in FLD.Files
'Get complete file name with path
strOldName = fil.Path
'Check the file has an underscore in the name
If InStr(strOldName, "_") > 0 Then
'Split the file on the underscore so we can get everything before it
strFileParts = Split(strOldName, "_")
'Build the new file name with everything before the
'first under score plus the extension
strNewName = strFileParts(0) & ".txt"
'Use the MoveFile method to rename the file
FSO.MoveFile strOldName, strNewName
End If
Next
'Cleanup the objects
Set FLD = Nothing
Set FSO = Nothing
My config file only has this:
Folder = "C:\Users\Lenovo\Desktop\RenameFile\Test - Copy"
Set fso = CreateObject("Scripting.FileSystemObject")
Set TS = fso.OpenTextFile("C:\Users\Lenovo\Desktop\RenameFile\ConfigPad.txt")
SrcFolder = TS.ReadLine
Set fldr = fso.GetFolder(SrcFolder)
Set Fls = fldr.files
For Each thing in Fls
If Left(thing.name, 1) = "_" AND IsNumeric(Mid(thing.name, 2, 8)) Then
thing.name = mid(thing.name, 10)
End If
Next
This assumes the first line in the config file is a path. It renames any files starting with an underscore and followed by 8 digits.
Please Try This
configfile = "Config File Name Here" 'Example : C:\Documents\Config.txt
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set tf = objFSO.OpenTextFile(configfile, 1)
Do Until tf.AtEndOfStream
cl = tf.ReadLine
If InStr(cl, "Folder = ") > 0 Then
Folder = Replace(Replace(cl,"Folder = ",""),chr(34),"")
tf.Close
Exit Do
End If
Loop
For Each File in objFSO.GetFolder(Folder).Files
If InStr(File.Name, "_") > 0 And IsNumeric(Mid(File.Name,InStr(File.Name, "_") + 1,8)) Then
NewName = Replace(File.Name,Mid(File.Name,InStr(File.Name, "_"),9),"")
objFSO.MoveFile File.Path, objFSO.GetParentFolderName(File.Path) & "\" & NewName
End If
Next
MsgBox "Task Complete", vbOKOnly, "Remove Time Stamp"

replacing XML values in For-Each and returning in function

The script I have here is attempting to do recurse through an XML file, storing each RegEx match (stored in a search array) into 2 result arrays; 1 for start date, 1 for end date.
Ubounds of both arrays are checked for equality then the text is passed to a function that uses XMLDOM to find the End_Date node in each parent node, then passes that text to another function, adding 30 days and then passing it back, replacing the previous value. Then it's supposed to write back the contents to the file and save it.
I've got a few problems here. 1. I can't get the +30 day value to be passed back to anything past the first parent node--memory space seems to retain the +30 day value from previous For-Each iteration. 2. I can't write anything back to the file.
I was initially writing for text files, but the format changed to XML as the requirements changed on our project.
I'd love to be able to do this all in XMLDOM in vbscript and just use functions to do specific data changes. But my main concern is my sloppy script not doing the basics.
Can anyone help me by pointing out the flaws in the loops I'm running? I've hit a wall and just can't seem to make any more progress!
Here's the XML file I'm reading(shortened to 2 Ad nodes w/ a ton of child nodes removed):
<?xml version="1.0" encoding="utf-8"?>
<XMLFeederRoot>
<ADS_CREATE_TIME>2016-06-07T01:35:39</ADS_CREATE_TIME>
<Ad>
<Ad_Number>d00524224</Ad_Number>
<Start_Date>2016-08-20T00:00:00</Start_Date>
<End_Date>2016-08-20T00:00:00</End_Date>
<Status>Run</Status>
</Ad><Ad>
<Ad_Number>d00524225</Ad_Number>
<Start_Date>2016-08-20T00:00:00</Start_Date>
<End_Date>2016-08-20T00:00:00</End_Date>
<Status>Run</Status>
</Ad>
</XMLFeederRoot>
Here's the script:
'Setting the Regular Expression object and setting occurrences to all in strings searched.
Set objRegEx= CreateObject("VBScript.RegExp")
objRegEx.Global= True
set Shell= createobject("wscript.shell")
Dim FSO, FLD, FIL, TS, strDate, strEDat, i, d, c
Dim strFolder, strContent, strPath
Const ForReading= 1, ForWriting= 2
strFolder= "C:\Scripts\Run"
Set FSO= CreateObject("Scripting.FileSystemObject")
'Get a reference to the folder you want to search
set FLD= FSO.GetFolder(strFolder)
'loop through the folder and get the files
For Each Fil In FLD.Files
'Open the file to read
Set TS= FSO.OpenTextFile(fil.Path, ForReading)
'Read the contents into a variable
strContent= TS.ReadAll
'Close the file
TS.Close
reDim arrMR(1,1)
arrMR(0,0)= "(\s+)(<Start_Date>(.*?)<\/Start_Date>)"
arrMR(1,0)= "(\s+)(<End_Date>(.*?)<\/End_Date>)"
For i= 0 to Ubound(arrMR)
objRegEx.Pattern= arrMR(i,0)
Set objMatches= objRegEx.Execute(strContent)
d=0
For Each objMatch in objMatches
If i= 0 Then
If d>0 Then
reDim Preserve arrStart(d)
Else
reDim arrStart(d)
End If
arrStart(d)= objMatches.Item(d).SubMatches(2)
'Wscript.Echo arrStart(d)
ElseIf i<> 0 Then
If d>0 Then
reDim Preserve arrEnd(d)
ReDim Preserve arrMatch1(d)
Else
reDim arrEnd(d)
ReDim arrMatch1(d)
End If
arrEnd(d)= objMatches.Item(d).SubMatches(2)
arrMatch1(d)= objMatches.Item(d).SubMatches(1)
End If
If objRegEx.Pattern<> arrMR(0,0) Then
If (ubound(arrStart)= ubound(arrEnd)) Then
'Wscript.Echo "Ubounds Match"
Parse strContent
strContent= Parse(strContent)
Else
'Wscript.Echo "Start & End Dates do not match"
End If
End If
d= d+ 1 'increment to next match
Next
Next
'Close the file
TS.Close
'Open the file to overwrite the contents
Set TS= FSO.OpenTextFile(fil.Path, ForWriting)
'Write the contents back
TS.Write strContent
'Close the current file
TS.Close
Next
'Clean up
Set TS= Nothing
Set FLD= Nothing
Set FSO= Nothing
Function Parse(ParseContent)
'Dim sFSpec : sFSpec = FSO.GetAbsolutePathName("C:\Users\j.levine\Desktop\XML Feeder Scripts\Test_Files\monvid.txt")
Dim oXML : Set oXML = CreateObject("Msxml2.DOMDocument.6.0")
Dim strXMLSDat, strXMLarrStartD, XMLEDat
oXML.setProperty "SelectionLanguage", "XPath"
oXML.async = False
oXML.loadXML(ParseContent)
If 0 = oXML.parseError Then
Dim sXPath3 : sXPath3 = "//XMLFeederRoot/Ad[End_Date=Start_Date]"
Dim ndlFnd : Set ndlFnd = oXML.selectNodes(sXPath3)
If 0 = ndlFnd.length Then
WScript.Echo sXPath, "not found"
ElseIf 0<> ndlFnd.length Then
'WScript.Echo "found", ndlFnd.length, "nodes for", sXPath
Dim ndCur, oldNode
For Each ndCur In ndlFnd
oldNode = oXML.selectsinglenode("//End_Date").text
oldNode= XMLSplitArray(oldNode) 'Pass current Date into Array and add 30 days & return as node text
Set newNode= oXML.selectSingleNode("//End_Date")
newNode.text= oldNode
WScript.Echo ndCur.xml
Next
'WScript.Echo "We have nothing to replace"
End If
Else
WScript.Echo oXML.parseError.reason
End If
Parse= ParseContent
End Function
Function XMLSplitArray(strval1)
dim XmlSA, XmlSA2, XMLEDat
XmlSA = split(strval1, "-")
XmlSA(2) = Left(XmlSA(2), 2)
strXMLDate = XmlSA(1) & "/" & XmlSA(2) & "/" & XmlSA(0)
strXMLDate30 = DateAdd("d", 30, strXMLDate)
XmlSA2 = split(strXMLDate30, "/")
'Add zero to the left
XmlSA2(0)= Right("0" & XmlSA2(0), 2)
XmlSA2(1)= Right("0" & XmlSA2(1), 2)
XmlSA2(1) = XmlSA2(1) & "T00:00:00"
XMLEDat = XmlSA2(2) & "-" & XmlSA2(0) & "-" & XmlSA2(1)
XMLSplitArray= XMLEDat
End Function
Thomas was right w/ the KISS method. I took a big step back, and started over.
Here's what I've come up with. It does what I need regarding the Date+30 and writing back to a file. I think this method is cleaner and will allow me to run my other text massaging through functions.
My questions about this new script are:
1. can this be done without having to write to a new file? Keeping to 1 file is easier.
2. Can I avoid cloning the node and deleting the original one and directly change the original node's value?
3. I seem to be missing how to get that last node <Status> onto it's own line.
Script:
Dim xmlDoc: Set xmlDoc = CreateObject("Msxml2.DOMDocument")
xmlDoc.Async = False
xmlDoc.load "C:\Scripts\Run\MonVid-SHORT.xml"
Dim xmldoc2: set xmldoc2 = CreateObject("Msxml2.DOMDocument")
Dim strSkeleton : strSkeleton= "<?xml version=""1.0"" encoding=""utf-8""?>" & _
"<XMLFeederRoot>" & _
"</XMLFeederRoot>"
xmldoc2.loadXML(strSkeleton)
xmldoc2.save "C:\Scripts\Copy\New_MonVid-Short.xml"
xmlDoc2.async = False
xmlDoc2.load "C:\Scripts\Copy\New_MonVid-Short.xml"
Dim sXPath : sXPath = "/XMLFeederRoot/Ad[Start_Date=End_Date]"
For Each n In XMLDoc.SelectNodes(sXpath)
set l = n.cloneNode(True)
q= l.selectSingleNode("/End_Date").text
strSDat=SplitArray(q)
l.removeChild(l.childNodes.item(2))
set Stat= l.selectSingleNode("/Status")
set Parent= Stat.parentNode
set EDate= xmlDoc2.createElement("End_Date")
EDate.appendChild xmlDoc2.createTextNode(strSDat)
Parent.insertBefore EDate, Stat
xmldoc2.documentElement.appendChild parent
Next
xmlDoc2.save xmldoc2.url
Function SplitArray(strval1)
dim SplitArray1, SplitArray2, strSDat
splitArray1 = split(strval1, "-")
splitArray1(2) = left(splitArray1(2), 2)
strDate1 = SplitArray1(1) & "/" & SplitArray1(2) & "/" & SplitArray1(0)
strDate30 = DateAdd("d", 30, strDate1)
SplitArray2 = split(strDate30, "/")
'Add zero to the left
If Len(SplitArray2(0))<2 Then
SplitArray2(0)= Right("0" & SplitArray2(0), 2)
End If
If Len(SplitArray2(1))<2 Then
SplitArray2(1)= Right("0" & SplitArray2(1), 2)
End If
SplitArray2(1) = splitArray2(1) & "T00:00:00"
strSDat = SplitArray2(2) & "-" & SplitArray2(0) & "-" & SplitArray2(1)
SplitArray= strSDat
End Function
Output File:
<?xml version="1.0" encoding="utf-8"?>
<XMLFeederRoot><Ad>
<Ad_Number>d00524224</Ad_Number>
<Start_Date>2016-08-20T00:00:00</Start_Date>
<End_Date>2016-09-19T00:00:00</End_Date><Status>Run</Status>
</Ad><Ad>
<Ad_Number>d00524225</Ad_Number>
<Start_Date>2016-08-20T00:00:00</Start_Date>
<End_Date>2016-09-19T00:00:00</End_Date><Status>Run</Status>
</Ad>
</XMLFeederRoot>
Since Text and XML files don't use file locks by default just overwrite the original file using xmlDoc.Save monvidPath.
Sub setAdEndDate(monvidPath)
Const sXPath = "/XMLFeederRoot/Ad/End_Date"
Set xmlDoc = CreateObject("Microsoft.XMLDOM")
xmlDoc.Async = "False"
xmlDoc.Load(monvidPath)
Set colNodes=xmlDoc.selectNodes(sXPath)
For Each n In colNodes
n.Text = SplitArray(n.Text)
Next
xmlDoc.Save monvidPath
End Sub
Function SplitArray(strval1)
Dim SplitArray1, SplitArray2, strSDat
splitArray1 = Split(strval1, "-")
splitArray1(2) = Left(splitArray1(2), 2)
strDate1 = SplitArray1(1) & "/" & SplitArray1(2) & "/" & SplitArray1(0)
strDate30 = DateAdd("d", 30, strDate1)
SplitArray2 = Split(strDate30, "/")
'Add zero to the left
If Len(SplitArray2(0))<2 Then
SplitArray2(0)= Right("0" & SplitArray2(0), 2)
End If
If Len(SplitArray2(1))<2 Then
SplitArray2(1)= Right("0" & SplitArray2(1), 2)
End If
SplitArray2(1) = splitArray2(1) & "T00:00:00"
strSDat = SplitArray2(2) & "-" & SplitArray2(0) & "-" & SplitArray2(1)
SplitArray= strSDat
End Function

Not getting the output for splitting the text files in vbscript

I have been using the following code to split my text file into two files.My original file only consists of 20 lines which i am trying to split into 2 files.Even when the script runs and i get the message at the end saying that the process is complete i can't see any splitted files at the output location.Please tell me what's the problem in the code;I am new to vbscript so please help me.Thanks in advance :)
Dim Counter
Const InputFile = "C:\Cs.txt"
Const OutputFile = "C:\Users\rmehta\Desktop"
Const RecordSize = 10
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile (InputFile, ForReading)
Counter = 0
FileCounter = 0
Set objOutTextFile = Nothing
Do Until objTextFile.AtEndOfStream
if Counter = 0 Or Counter = RecordSize Then
Counter = 0
FileCounter = FileCounter + 1
if Not objOutTextFile is Nothing then objOutTextFile.Close
Set objOutTextFile = objFSO.OpenTextFile( OutputFile & "_" & FileCounter & ".txt", ForWriting, True)
end if
strNextLine = objTextFile.Readline
objOutTextFile.WriteLine(strNextLine)
Counter = Counter + 1
Loop
objTextFile.Close
objOutTextFile.Close
Msgbox "Split process complete"
If you leave out all the spurious fat (the Textstream has a line counter and the first output file can be opened before the loop), you get
Option Explicit
Const cnSize = 10
Dim oFS : Set oFS = CreateObject("Scripting.FileSystemObject")
Dim sDir : sDir = "..\testdata\18308970"
Dim tsIn : Set tsIn = oFS.OpenTextFile(oFS.BuildPath(sDir, "all.txt"))
Dim nFCnt : nFCnt = 0
Dim tsOut : Set tsOut = oFS.CreateTextFile(oFS.BuildPath(sDir, nFCnt & "-part.txt"))
Do Until tsIn.AtEndOfStream
If 0 = tsIn.Line Mod cnSize Then
tsOut.Close
nFCnt = nFCnt + 1
Set tsOut = oFS.CreateTextFile(oFS.BuildPath(sDir, nFCnt & "-part.txt"))
End If
tsOut.WriteLine tsIn.ReadLine()
Loop
tsIn.Close
tsOut.Close
That this 'works' - if you have the folder, input file, and permissions - is obvious. In your code, the problem
>> Const OutputFile = "C:\Users\rmehta\Desktop"
>> FileCounter = 0
>> WScript.Echo OutputFile & "_" & FileCounter & ".txt"
>>
C:\Users\rmehta\Desktop_0.txt
is is deeply hidden.

subscript out of range error in vbscript

Can someone look at the below script and tell me why it's throwing this error subscript out of range error in vbscript ..In the text file there are two entries it writes to the file correctly but then it throws an error while exiting the loop so it never calls the other function..I think it's trying to run 3 times but there are just 2 entries in the text file
The text file is in this format
Format.css Shared
Design.css Shared
Dim strInputPath1
Dim txsInput1,txsOutput
Dim FSO
Dim Filename
Set FSO = CreateObject("Scripting.FileSystemObject")
strOutputPath = "C:\txt3.txt"
Set txsOutput = FSO.CreateTextFile(strOutputPath)
Set re = New RegExp
re.Pattern = "\s+"
re.Global = True
Set f = FSO.OpenTextFile("C:\Users\spadmin\Desktop\Main\combination.txt")
Do Until f.AtEndOfStream
tokens = Split(Trim(re.Replace(f.ReadLine, " ")))
extension = Split(tokens(0),".")
strInputPath1 = "C:\inetpub\wwwroot\Test\files\" & tokens(1) & "\" & extension(1) & "\" & tokens(0)
Set txsInput1 = FSO.OpenTextFile(strInputPath1, 1)
WScript.Echo strInputPath1
txsOutput.Writeline txsInput1.ReadAll
Loop
WScript.Echo "Calling"
txsInput1.Close
txsOutput.Close
f.Close
Call CreateCSSFile()
''''''''''''''''''''''''''''''''''''
' Merge Css Files
''''''''''''''''''''''''''''''''''''
Sub CreateCSSFile()
WScript.Echo "Called"
Dim FilenameCSS
Dim strInputPathCSS
Dim txsInputCSS,txsOutputCSS
Dim FSOCSS
Set FSOCSS = CreateObject("Scripting.FileSystemObject")
strOutputPathCSS = "C:\txt4.txt"
Set txsOutputCSS = FSOCSS.CreateTextFile(strOutputPath)
Set re = New RegExp
re.Pattern = "\s+"
re.Global = True
Set fCSS = FSOCSS.OpenTextFile("C:\Users\spadmin\Desktop\TestingTheWebService\combination.txt")
Do Until fCSS.AtEndOfStream
tokensCSS = Split(Trim(re.Replace(fCSS.ReadLine, " ")))
extensionCSS = Split(tokensCSS(0),".")
strInputPathCSS = "C:\inetpub\wwwroot\EpsShared\c\" & tokensCSS(1) & "\" & extensionCSS(1) & "\" & tokensCSS(0)
Set txsInputCSS = FSOCSS.OpenTextFile(strInputPathCSS, 1)
txsOutputCSS.Writeline txsInputCSS.ReadAll
Loop
fCSS.Close
txsInputCSS.Close
txsOutputCSS.Close
Set FSOCSS = Nothing
End Sub
If your file contains trailing blank lines, applying Split() may return arrays with less than 2 elements. In that case token(1) should throw a 'subscript out of range' error.
You should always check, if Split() workes as expected:
tokens = Split(Trim(re.Replace(f.ReadLine, " ")))
If 1 = UBound(tokens) Then
extension = Split(tokens(0),".")
If 1 = UBound(extension) Then
strInputPath1 = "..." & tokens(1) & "..."
Else
... parse error ...
End If
Else
... parse error or just trailing blank lines? ...
End If

Resources