Dim strPath, strOutputPath
If WScript.Arguments.Count = 2 Then
strPath = WScript.Arguments.Item(0)
strOutputPath = WScript.Arguments.Item(1)
Else
Wscript.Echo "Usage: cscript AddContent.vbs ""C:\path"" ""C:\outputpath"""
Wscript.Quit
End If
Const OutPutFileName = "OutputFile.csv"
Dim objFS
Set objFS = CreateObject("Scripting.FileSystemObject")
If objFS.FolderExists(strPath) And objFS.FolderExists(strOutputPath) Then
WScript.Echo "Working in directory: " & strPath
Dim objFolder
Set objFolder = objFS.GetFolder(strPath)
Set outputFile = objFS.OpenTextFile(strOutputPath & "\" & OutPutFileName, 2, True) 'write/replace - don't append - create
Dim strHeader, strLine
For Each objFile in objFolder.Files
If LCase(Right(objFile.Name, 4)) = LCase(".csv") Then 'only for .CSV files
WScript.Echo "Processing file for headers: " & objFile.Name
Set inputFile = objFS.OpenTextFile(strPath & "\" & objFile.Name, 1) 'reading
Do While Not inputFile.AtEndOfStream
strLine = Split(inputFile.ReadLine, ",", -1, 1)
If Ubound(strLine) > 0 Then 'no content in this line
If Not Instr(1, (strHeader & ","), (strLine(0) & ","), 1) > 0 Then 'find if we have this header
If Len(strHeader) > 0 Then strHeader = strHeader & ","
strHeader = strHeader & strLine(0)
End If
End If
Loop
inputFile.Close
Set inputFile = Nothing
End If
Next
outputFile.WriteLine strHeader 'let's write our first line - the headers we have
WScript.Echo "..Finsihed processing the headers - wrote to file: " & strOutputPath & "\" & OutPutFileName
Dim arrSplitHeader, iHeaders, cntHeaders
arrSplitHeader = Split(strHeader, ",", -1, 1)
iHeaders = Ubound(arrSplitHeader)
Dim arrLines()
ReDim arrLines((iHeaders))
Dim strOutLine
For Each objFile in objFolder.Files
For cntHeaders = 0 To iHeaders 'cleanup
arrLines(cntHeaders) = ""
Next
If LCase(Right(objFile.Name, 4)) = LCase(".csv") Then 'only for .CSV files
WScript.Echo "Processing file for data: " & objFile.Name
Set inputFile = objFS.OpenTextFile(strPath & "\" & objFile.Name, 1) 'reading
Do While Not inputFile.AtEndOfStream
strLine = Split(inputFile.ReadLine, ",", -1, 1)
If Ubound(strLine) > 0 Then 'we do have data
For cntHeaders = 0 To iHeaders
If arrSplitHeader(cntHeaders) = strLine(0) Then
arrLines(cntHeaders) = strLine(1)
Exit For
End If
Next
End If
Loop
inputFile.Close
Set inputFile = Nothing
strOutLine = ""
For cntHeaders = 0 To iHeaders 'writeout
If Len(strOutLine) > 0 Then strOutLine = strOutLine & ","
strOutLine = strOutLine & arrLines(cntHeaders)
Next
outputFile.WriteLine strOutLine
End If
Next
outputFile.Close
Set outputFile = Nothing
WScript.Echo "..Finsihed - wrote to file: " & strOutputPath & "\" & OutPutFileName
Set objFolder = Nothing
End If
Set objFS = Nothing