.vbs Help me loop this through a directory - vbscript

I have written a script that works. What it does now is it looks through a directory to a given file and returns what is on the second row fourth tab (RXC193) and renames the file to that of which it found from a file like this:
#Program #RxBIN #RXPCN #RxGroup #MemberID #WebsiteE #WebsiteS #VerticalLogo #TextLogo
RXCUT 013824 RXCUT RXC193 RXC5FHXF9 www.rxcut.com/HBG www.rxcut.com/HBG/es P:\RxCut\In Design Implementation\RXC193
What I need this script to be able to do is loop through the directory and rename all files by this RXC#####. Here is the script:
Call TwoDimensionArrayTest
Sub TwoDimensionArrayTest
' Version 1.0
' Writtem by Krystian Kara
' Dated 25-Jan-2009
Dim fso
Dim oFile
Dim arrline
Dim arrItem
Dim objFolder
Dim i
Dim arrMain()
Dim sFileLocation, strResults
Const forReading = 1
' The file contains on each line:
' Text1 (tab) Text2 (tab) Text3 (tab) Text4
' Text5 (tab) Text6 (tab) Text7 (tab) Text8
'etc etc
Set fso = CreateObject("Scripting.FileSystemObject")
sFileLocation = "file 2.txt"
Set oFile = fso.OpenTextFile(sFileLocation, forReading, False)
Do While oFile.AtEndOfStream <> True
strResults = oFile.ReadAll
Loop
' Close the file
oFile.Close
' Release the object from memory
Set oFile = Nothing
' Return the contents of the file if not Empty
If Trim(strResults) <> "" Then
' Create an Array of the Text File
arrline = Split(strResults, vbNewLine)
End If
For i = 0 To UBound(arrline)
If arrline(i) = "" Then
' checks for a blank line at the end of stream
Exit For
End If
ReDim Preserve arrMain(i)
arrMain(i) = Split(arrline(i), vbTab)
Next
fso.MoveFile "file 2.txt", arrMain(1)(3) & ".txt"
End Sub ' TwoDimensionArrayTest
Thanks in advance,
Joe

One approach is to parameterize the file name in your sub-procedure so it can be called multiple times for different files, like this:
Sub TwoDimensionArrayTest(fileName) 'you may want a more descriptive name
' ...
sFileLocation = fileName
' ...
End Sub
Then, write a loop that goes through your directory, calling your sub each time around:
Dim fso, folder
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder("Your Folder Name")
For Each file In folder.Files
TwoDimensionArrayTest file.Path
Next

Here is the Final Error free code! Finally have it searching through my directory of Tab-delimited.txt files and grabbing from the second row third tab (group number) then renaming the files to its corrisponding group number! YAY!
heres final error free code!:
Call TwoDimensionArrayTest
Sub TwoDimensionArrayTest
Dim fso
Dim oFile
Dim arrline
Dim arrItem
Dim i
Dim arrMain()
Dim sFileLocation, strResults
Const forReading = 1
strFolder = "C:\Documents and Settings\jmituzas.NMCLLC\Desktop\desktop2\New Folder (2)\datafiles"
Set objFSO = CreateObject("Scripting.FileSystemObject")
For Each objFile In objFSO.GetFolder(strFolder).Files
If Right(LCase(objFile.Name), 4) = LCase(".txt") Then
' The file contains on each line:
' Text1 (tab) Text2 (tab) Text3 (tab) Text4
' Text5 (tab) Text6 (tab) Text7 (tab) Text8
'etc etc
Set fso = CreateObject("Scripting.FileSystemObject")
sFileLocation = objFile.Name
Set oFile = fso.OpenTextFile(objFile.Name, forReading, False)
Do While oFile.AtEndOfStream <> True
strResults = oFile.ReadAll
Loop
' Close the file
oFile.Close
' Release the object from memory
Set oFile = Nothing
' Return the contents of the file if not Empty
If Trim(strResults) <> "" Then
' Create an Array of the Text File
arrline = Split(strResults, vbNewLine)
End If
For i = 0 To UBound(arrline)
If arrline(i) = "" Then
' checks for a blank line at the end of stream
Exit For
End If
ReDim Preserve arrMain(i)
arrMain(i) = Split(arrline(i), vbTab)
Next
fso.MoveFile sFileLocation, arrMain(1)(3) & ".txt"
End If
Next
End Sub ' TwoDimensionArrayTest

Related

How can I get file details in subfolders recursively?

I'm trying to compile a list of specific details about the music files on my computer, but my knowledge of VBS is limited. (Actually, I've done some VBA, but no VBS before.) I found two scripts online: one gets the file details in a folder and the other lists the names of subfolders and files recursively. I'm trying to combine the two but I'm running into problems because the first script starts with CreateObject("Shell.Application") and the second starts with CreateObject("Scripting.FileSystemObject"). This (i.e., Shell vs. FSO) is one of the areas of VBS scripting about which my knowledge is lacking, to put it mildly.
The incompatibility in my script appears in the For Each objFile in colFiles loop, which I inserted from the "Shell script" I referred to above. What can I do to make this script work?
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Dim StartFolder, FileName, fso, MyFile, Tabs, arrDetails(4)
Tabs = ""
arrDetails(0) = 0
arrDetails(1) = 1
arrDetails(2) = 27
arrDetails(3) = 28
StartFolder = "C:\Users\user\Music\MP3s"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(StartFolder)
FileName = "C:\Users\user\Documents\MP3 File Details.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile = fso.OpenTextFile(FileName, ForAppending, True, True)
MyFile.WriteLine objFolder.Path
ShowSubfolders objFSO.GetFolder(StartFolder), Tabs, arrDetails
Sub ShowSubFolders(Folder, ByVal Tabs, arrDetails)
Dim TabsFolder, TabsFiles, FileLine, arrText(4), i, d
TabsFolder = Tabs & "" & vbtab & ""
For Each Subfolder in Folder.SubFolders
MyFile.WriteLine
MyFile.WriteLine TabsFolder & Subfolder.Name
TabsFiles = TabsFolder & "" & vbtab & ""
Set objSubFolder = objFSO.GetFolder(Subfolder.Path)
Set colFiles = objSubFolder.Files
'Original inserted code for getting file details
' For Each strFileName in objFolder.Items
' For i = 0 to 3
' d = arrDetails(i)
' arrText(i) = objFolder.GetDetailsOf(strFileName, d)
' Next
'
' FileLine = arrText(0)
' For i = 1 to 3
' FileLine = FileLine & vbtab & arrText(i)
' Next
' MyFile.WriteLine FileLine
' Next
'Attempt to make code compatible with rest of script
For Each objFile in colFiles
If LCase(InStr(1, objFile.Name, ".mp3")) > 1 then
For i = 0 to 3
d = arrDetails(i)
arrText(i) = colFiles.GetDetailsOf(objFile, d)
Next
FileLine = arrText(0)
For i = 1 to 3
FileLine = FileLine & vbtab & arrText(i)
Next
MyFile.WriteLine TabsFiles & FileLine
End If
Next
ShowSubFolders Subfolder, TabsFolder, arrDetails
Next
End Sub
MyFile.Close
You do need both the FileSystemObject and the Windows Shell object in this case. You use the FileSystemObject to loop through the folders. In each folder, you then use the Windows Shell object to get the file details.
Here's a modified ShowSubFolders Sub that will work as expected:
Sub ShowSubFolders(Folder, Tabs, arrDetails)
Dim TabsFolder, TabsFiles, FileLine, arrText(4), i, d
Dim objShell
Dim objFolder
Dim objSubfolder
Dim objFiles
Dim objFile
Dim sFileName
Set objShell = CreateObject("Shell.Application")
TabsFolder = Tabs & "" & vbTab & ""
For Each objSubfolder In Folder.SubFolders
' Write subfolder to file
MyFile.WriteLine
MyFile.WriteLine TabsFolder & objSubfolder.Name
' Increment tab position
TabsFiles = TabsFolder & "" & vbTab & ""
Set objFolder = objShell.Namespace(objSubfolder.Path)
Set objFiles = objSubfolder.Files
For Each sFileName In objFolder.Items
' Check if file is MP3
If InStr(1, LCase(sFileName), ".mp3") > 0 Then
' Get file details
For i = 0 To 3
d = arrDetails(i)
arrText(i) = objFolder.GetDetailsOf(sFileName, d)
Next
' Build file information line
FileLine = arrText(0)
For i = 1 To 3
FileLine = FileLine & vbTab & arrText(i)
Next
' Write file information to file
MyFile.WriteLine TabsFiles & FileLine
End If
Next
' Call recursively to handle subfolders
ShowSubFolders objSubfolder, TabsFolder, arrDetails
Next
End Sub
The code you had commented out was good and made accessing extended file properties (like length and bitrate in your case) possible using the arrDetails you have.
Also included in this revised sub is the fix Arno Van Boven mentioned in the comments regarding flipping InStr and LCase.

I want to search for the particular word and then after that word on each line i want to add ; in the start

Using below code I was able to add ; in the start of each line but the I want to add ; after a particular word is found e.g. [Abc]. How to do this using VBScript?
Const ForReading=1
Const ForWriting=2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set f = objFSO.OpenTextFile("D:\sam.txt", ForReading)
Do Until f.AtEndOfStream
strText = f.ReadLine
If Len(strText) = 0 Then
blnFound = True
MsgBox "blank line found"
strText = vbNewLine & strText
strContents = strContents & strText & vbCrlf
Else
strText = ";" & strText
strContents = strContents & strText & vbCrlf
End If
Loop
f.Close
Set f = objFSO.OpenTextFile("D:\sam.txt", Forwriting)
f.WriteLine strContents
f.Close
Sam.txt is containing some lines, e.g.
Hi, need help
This is a sample text file
[Abc]
How are you
Hope you are doing well!
So I want the output sam.txt file should have below data inside it:
Hi, need help
This is a sample text file
[Abc]
;How are you
;Hope you are doing well!
So, basically, you have an INI-style file and want the entries in a particular section commented. That can be achieved like this:
filename = "D:\sam.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
txt = Split(fso.OpenTextFile(filename).ReadAll, vbNewLine)
disable = False
For i = 0 To UBound(txt)
If Left(txt(i), 1) = "[" Then
If txt(i) = "[Abc]" Then
disable = True
Else
disable = False
End If
End If
If disable Then txt(i) = ";" & txt(i)
Next
fso.OpenTextFile(filename, 2).Write Join(txt, vbNewLine)
Try this
Option Explicit
Dim FSO ' Object
Set FSO = CreateObject("Scripting.FileSystemObject")
Dim ReadTxtFile, WriteTxtFile ' Object
Dim TextLine, TextLineToWrite ' String
Dim AddStr' bool
' Open both text file in the same time
Set ReadTextFile = FSO.OpenTextFile("Sam.txt", 1) ' Open file to read
Set WriteTextFile = FSO.OpenTextFile("Sam_new.txt", 2, True) ' Open file to write
' Do read file as normal but add a switch
' Write original text line to text file while switch is disabled
' Add str to the text line and write once switch is trigger
AddStr = False ' Add str disabled
Do Until ReadTextFile.AtEndOfStream ' Start Read
Textline = ReadTextFile.Readline
If AddStr = True Then ' If add str enabled
TextLineToWrite = ";" & Textline ' Add string
Else ' if add str disabled
TextLineToWrite = Textline ' write original line
End If
If Trim(Textline) = "[ABC]" Then ' If indicator read
AddStr = True ' add str write
End if
WriteTextFile.WriteLine TextLineToWrite ' Write file when each line is read
Loop
ReadTextFile.Close
WriteTextFile.Close
msgbox "Done"

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"

Append text to text file if it already exists

I have a script which is working, to replace some characters in a fixed width file (starting from row 2 onward).
What want to avoid overwriting the target file if it already exists. Instead, if it exists, to append the rows (from row 2 onwards of the source file) to the end of the target file. I am struggling to find a thread with a proper suggestion. This is the current code:
Dim objFSO
dim objFile
dim thisLine
Set objFSO = CreateObject("Scripting.FileSystemObject")
If (objFSO.FileExists("C:\Users\Dimitar\Desktop\BPSDRC\PAYBOTH.dat")) Then
Set objFile = objFSO.GetFile("C:\Users\Dimitar\Desktop\BPSDRC\PAYBOTH.dat")
Else
WScript.Quit()
End If
If objFile.Size > 0 Then 'make sure the input file is not empty
Set inputFile = objFSO.OpenTextFile("C:\Users\Dimitar\Desktop\BPSDRC\PAYBOTH.dat", 1) 'Replace the filename here
set outputFile = objFSO.CreateTextFile("C:\Users\Dimitar\Desktop\BPSDRC\PAYIMP.dat", TRUE) 'replace it with output filename
' first line - leave it as it is
thisLine = inputFile.ReadLine
newLine = thisLine
outputFile.WriteLine newLine
'all remaining lines - read them and replace the middle part with 18 zeroes
do while not inputFile.AtEndOfStream
thisLine = inputFile.ReadLine ' Read an entire line into a string.
'the zeroes are to fix issue N1 (payment in other amt)
'the CDF are to fix issue N2 (payment in local amt)
newLine = mid(thisLine,1,47) & "000000000000000000" & mid(thisLine,66,121) & "CDF" & mid(thisLine,190)
outputFile.WriteLine newLine
loop
inputFile.Close
outputFile.Close
objFSO.DeleteFile "C:\Users\Dimitar\Desktop\BPSDRC\PAYBOTH.dat"
end if
Open the file for appending
Option Explicit
Const ForReading = 1, ForAppending = 8
Dim inputFileName, outputFileName
inputFileName = "C:\Users\Dimitar\Desktop\BPSDRC\PAYBOTH.dat"
outputFileName = "C:\Users\Dimitar\Desktop\BPSDRC\PAYIMP.dat"
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FileExists( inputFileName ) Then
WScript.Quit
End If
If fso.GetFile( inputFileName ).Size < 1 Then
WScript.Quit
End If
Dim newFile, inputFile, outputFile
newFile = Not fso.FileExists( outputFileName )
Set inputFile = fso.OpenTextFile( inputFileName, ForReading )
Set outputFile = fso.OpenTextFile( outputFileName, ForAppending, True )
Dim lineBuffer
lineBuffer = inputFile.ReadLine()
If newFile Then
outputFile.WriteLine lineBuffer
End If
Do While Not inputFile.AtEndOfStream
lineBuffer = inputFile.ReadLine
lineBuffer = mid(lineBuffer,1,47) & "000000000000000000" & mid(lineBuffer,66,121) & "CDF" & mid(lineBuffer,190)
outputFile.WriteLine lineBuffer
Loop
inputFile.Close
outputFile.Close
fso.DeleteFile inputFileName

VBS Script tab not null

Earlier I have made a script to grab certain lines from a tabbed delimited text file, first row with each of the following rows into its own .txt file. (so these .txt files are only 2 rows of text)
Then it would move each .txt file by what text it found in the given tab in this case it was (1)(3) (second row - forth tab)
here is the code for the first part...
Call TwoDimensionArrayTest
Sub TwoDimensionArrayTest
Dim fso
Dim oFile
Dim arrline
Dim arrItem
Dim i
Dim arrMain()
Dim sFileLocation, strResults
Const forReading = 1
strFolder = "\\nas001\Production\RxCut\In Design Implementation\build\" '"
Set objFSO = CreateObject("Scripting.FileSystemObject")
For Each objFile In objFSO.GetFolder(strFolder).Files
If Right(LCase(objFile.Name), 4) = LCase(".txt") Then
''# The file contains on each line:
''# Text1 (tab) Text2 (tab) Text3 (tab) Text4
''# Text5 (tab) Text6 (tab) Text7 (tab) Text8
''# etc etc
Set fso = CreateObject("Scripting.FileSystemObject")
sFileLocation = objFile.Name
Set oFile = fso.OpenTextFile(objFile.Name, forReading, False)
Do While oFile.AtEndOfStream <> True
strResults = oFile.ReadAll
Loop
''# Close the file
oFile.Close
''# Release the object from memory
Set oFile = Nothing
''# Return the contents of the file if not Empty
If Trim(strResults) <> "" Then
''# Create an Array of the Text File
arrline = Split(strResults, vbNewLine)
End If
For i = 0 To UBound(arrline)
If arrline(i) = "" Then
''# checks for a blank line at the end of stream
Exit For
End If
ReDim Preserve arrMain(i)
arrMain(i) = Split(arrline(i), vbTab)
Next
fso.MoveFile sFileLocation, arrMain(1)(3) & ".txt"
End If
Next
End Sub ''# TwoDimensionArrayTest
Now moving on to the next part...
ok I have a tabbed delimited text file and in this file we have specified on first row 5th tab co-brand, 6th tab tri-brand, and 7th generic.
second row we have the directory path to whichever it maybe either co-brand, tri-brand or generic.
What I want to be able to do is move a given file we can call "group.txt" to either of those co-brand, tri-brand, or generic directories depending upon which field is NOT NULL.
How can I accomplish this? Would be nice to just be able to incorporate this into the last script towards the end where specified:
fso.MoveFile sFileLocation, arrMain(1)(3) & ".txt"
of course would depend from here what I mentioned above about the NOT NULL field.
Any help is greatly appreciated,
Joe
my guess is something like this at the end (maybe):
If not isNull(Rs("arrMain(1)(4)")) Then
Set sDirectory = "/co-brand"
End If
If not isNull(Rs("arrMain(1)(5)")) Then
Set sDirectory = "/tri-brand"
End If
If not isNull(Rs("arrMain(1)(6)")) Then
Set sDirectory = "/generic"
End If
fso.MoveFile sFileLocation, sDirectory, arrMain(1)(3) & ".txt"

Resources