Read configuration information from file into VBS array [duplicate] - vbscript

This question already has answers here:
Read data from ini file
(3 answers)
Closed 8 months ago.
I've written a vbs script to try delete all files over a certain age from pre-defined subfolders within a directory.
These subfolders are defined in a configuration file:
[folders]
des
dcs
I'm trying to load this data into a VBS script during runtime. The config file will be located in the same folder as the VBS script, in a subfolder called Config.
I basically want the values under [folder] stored in an array. Below is an example where I've hardcoded this using the variable codes.
Can someone please assist?
Set oFileSys = WScript.CreateObject("Scripting.FileSystemObject")
sRoot = "C:\project\Target"
today = Date
nMaxFileAge = 3
codes = Array("des", "dcs") 'hardcoded for now
For Each code in codes
textFilePath = oFileSys.BuildPath(sRoot, code)
remove_files(textFilePath)
Next
Function remove_files(path)
Set oFolder = oFileSys.GetFolder(path)
Set aFiles = oFolder.Files
Set aSubFolders = oFolder.SubFolders
For Each file in aFiles
dFileCreated = FormatDateTime(file.DateCreated, "2")
if DateDiff("d", dFileCreated, today) > nMaxFileAge Then
file.Delete(True)
End If
Next
For Each folder in aSubFolders
remove_files(folder.Path)
Next
End Function
Edit: It doesn't really matter what type of file the configuration file is. Just somewhere I can define a list of folder and read it into VBS.
The answer someone else has linked to before closing my question doesn't answer the question. See my solution below.

I managed to find some code elsewhere to help. Basically I just stored in the folder names in a text file, and read those in:
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objOpen = objFSO.OpenTextFile("C:\project\Target\test.txt", ForReading)
Dim code()
sRoot = "C:\project\Target"
today = Date
nMaxFileAge = 3
FileContent = objOpen.ReadAll
msgbox FileContent
codes = Split(FileContent, VbCrLF)
objOpen.Close
Set objOpen = Nothing
For Each code in codes
textFilePath = objFSO.BuildPath(sRoot, code)
msgbox textFilePath
remove_files(textFilePath)
Next
Function remove_files(path)
Set oFolder = objFSO.GetFolder(path)
Set aFiles = oFolder.Files
Set aSubFolders = oFolder.SubFolders
For Each file in aFiles
dFileCreated = FormatDateTime(file.DateCreated, "2")
if DateDiff("d", dFileCreated, today) > nMaxFileAge Then
file.Delete(True)
End If
Next
For Each folder in aSubFolders
remove_files(folder.Path)
Next
End Function

Related

How to rename a file and overwrite existing in VBS?

I already an existing vbs script to take one file (titled "Running_12345.xlsx") from one location and put it in the folder titled "Folder". This is an hourly file that has a long name based on what time it was run.
Now, I want to rename the file just "Running.xlsx" to remove the constantly changing file name. Initially, this code works, but for any subsequent occurence, it fails because the "Running.xlsx" file has already been renamed once and now already exists. How do I add overwrite logic to this code:
dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
set oFldr = fso.getfolder("folder")
for each ofile in oFldr.Files
if lcase(fso.GetExtensionName(ofile.Name)) = "xlsx" then
ofile.name = "Running.xlsx"
Exit for
end if
Next
Duh, just delete the file first. The code below does what I want:
dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
set oFldr = fso.getfolder("C:\Users\...\Desktop\MosaicTransforms\")
fso.DeleteFile("C:\Users\...\Desktop\MosaicTransforms\MosaicFile.xlsx")
for each ofile in oFldr.Files
if lcase(fso.GetExtensionName(ofile.Name)) = "xlsx" then
ofile.name = "MosaicFile.xlsx"
Exit for
end if
Next

VBS script to rename files using the pathname

i am new to VBS scripting and I have done few stuff with Excel VBA before. Now I have a script which renames single files with the pathname of the files (truncated to 4 letter each))see below. It is some script which I modified a bit to fit my purpose. However, I would like to automatize the file rename process and rename all files in a folder and its subfolders in the same way the scipt works for single files. Can anybody help me with this question?
Set Shell = WScript.CreateObject("WScript.Shell")
Set Parameter = WScript.Arguments
For i = 0 To Parameter.Count - 1
Set fso = CreateObject("Scripting.FileSystemObject")
findFolder = fso.GetParentFolderName(Parameter(i))
PathName = fso.GetAbsolutePathName(Parameter(i))
FileExt = fso.GetExtensionName(Parameter(i))
Search = ":"
findFolder2= Right(PathName, Len(PathName) - InStrRev(PathName, Search))
arr = Split(findFolder2, "\")
For j=0 To UBound(arr)-1
arr(j) = ucase(Left(arr(j), 4))
Next
joined = Join(arr, "%")
prefix = right(joined, len(joined)-1)
fso.MoveFile Parameter(i), findFolder + "\" + prefix
next
Hoping that I can get some useful ideas.
Herbie
Walking a tree requires recursion, a function calling itself for each level.
On Error Resume Next
Set fso = CreateObject("Scripting.FileSystemObject")
Dirname = InputBox("Enter Dir name")
ProcessFolder DirName
Sub ProcessFolder(FolderPath)
On Error Resume Next
Set fldr = fso.GetFolder(FolderPath)
Set Fls = fldr.files
For Each thing in Fls
msgbox Thing.Name & " " & Thing.DateLastModified
Next
Set fldrs = fldr.subfolders
For Each thing in fldrs
ProcessFolder thing.path
Next
End Sub
From Help on how to run another file.
Set Shell = WScript.CreateObject("WScript.Shell")
shell.Run(strCommand, [intWindowStyle], [bWaitOnReturn])
So outside the loop,
Set Shell = WScript.CreateObject("WScript.Shell")
And in the loop
shell.Run("wscript Yourscript.vbs thing.name, 1, True)
Also the VBS help file has recently been taken down at MS web site. It is available on my skydrive at https://1drv.ms/f/s!AvqkaKIXzvDieQFjUcKneSZhDjw It's called script56.chm.

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_")

comparing/copying largest files to new folder

What I wish to do is:
Copy files from a variety of sub-folders under a single main folder to a destination folder.
Three options when copying:
If no file in destination folder exists then copy.
If file exists, copy over if filesize is larger than destination file.
If file exists and both are the same filesize compare date/time and copy over if most recent.
Here is my pseudocode so far:
Dim filesys, strSourceFile, strDestFolder, strDestFile
Set filesys = CreateObject("Scripting.FileSystemObject")
strSourceFile = S:\SoCal\Section_2\*\Autogen\texture\*.agn
strDestFolder = F:\ADDON_SCENERY\simwestSOCAL\texture
strDestFile = F:\ADDON_SCENERY\simwestSOCAL\texture\*.agn
COPY each file in strSourceFolder
If IsEmpty (SourceFile, DestFolder)
Else If (SourceFile FileSize > DestFile)
Else If (SourceFile DateTime > DestFile DateTime)
Then 'keep/copy most recent file
End if
Am I on the right track?
Do I need to add a Loop?
Can one compare file sizes? All my research has found nothing yet on this.
Can I compare Date and Time against files?
As an update to my original post... (hope I am following forum rules correctly),
I have spent the last several weeks non-stop just reading-reading-reading and testing-failure-testing. I am happy to say (and a little proud), that I have completed my very first script... and it appears to work as planned but for just one file. I now need to convert this to work on all files inside my 'sourcefolder'.
I am a bit "brain dead" from this so any direction on converting this would be most appreciated. I know I need loops but what type and where? Do I rename everything referring to a file to a folder or use '*.txt' for files? In the meantime I will keep studying.
Here is my script (yea, lot's of MsgBox's so I could follow along the script path):
dim dFolder
dFolder = "S:\Scripting Workfolder\destfolder\"
dim dFile
dFile= "S:\Scripting Workfolder\destfolder\File 1.txt"
dim sFile
sFile = "S:\Scripting Workfolder\sourcefolder\File 1.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
'Check to see if the file already exists in the destination folder
If Not fso.FileExists(dFile) Then
MsgBox "File does not exist - will copy over to dFolder"
fso.CopyFile sFile, dFolder, true
Elseif fso.FileExists(dFile) Then
MsgBox "File already exist in destination folder determine largest"
ReplaceIfLarger sFile, dFile
End If
Sub ReplaceIfLarger(sFile, dFile)
const overwrite_existing = true
dim objFSO
set objFSO = createobject("Scripting.FileSystemObject")
dim objSourceFile
set objSourceFile = objFSO.GetFile(sFile)
'dim kbSourceSize
kbSourceSize = objSourceFile.size
dim objTargetFile
set objTargetFile = objFSO.GetFile (dFile)
'dim kbTargetSize
kbTargetSize = objTargetFile.size
If kbSourceSize > kbTargetSize Then
MsgBox "Source file is LARGER and will overwrite to dest folder"
objFSO.CopyFile objSourceFile.Path, objTargetFile.Path, overwrite_existing
ElseIf kbSourceSize < kbTargetSize Then
MsgBox "Source file is smaller - Will not overwrite to dest folder"
Else
ReplaceIfNewer sFile, dFile
End If
End Sub
Sub ReplaceIfNewer(sFile, dFile)
MsgBox "Both files exist and are the same size. Keep newest file"
const overwrite_existing = true
dim objFSO
set objFSO = createobject("Scripting.FileSystemObject")
dim dtmSourceFile
set dtmSourceFile = objFSO.GetFile(sFile)
dim dtmTargetFile
set dtmTargetFile = objFSO.GetFile(dFile)
If (dtmSourceFile.DateLastModified > dtmTargetFile.DateLastModified) then
MsgBox "Source File is Newer than Target File - Overwrite Target file"
objFSO.CopyFile dtmSourceFile.Path, dtmTargetFile.Path, overwrite_existing
Else
MsgBox "Source File is Older than Target File - Will not overwrite file"
End If
End Sub

Read and write into a file using VBScript

How can we read and write some string into a text file using VBScript? I mean I have a text file which is already present so when I use this code below:-
Set fso = CreateObject("Scripting.FileSystemObject" )
Set file = fso.OpenTextFile("C:\New\maddy.txt",1,1)
This opens the file only for reading but I am unable to write anything
and when I use this code:-
Set fso = CreateObject("Scripting.FileSystemObject" )
Set file = fso.OpenTextFile("C:\New\maddy.txt",2,1)
I can just use this file for writing but unable to read anything. Is there anyway by which we can open the file for reading and writing by just calling the OpenTextFile method only once.
I am really new to VBScript. I am only familiar with C concepts.
Is there any link to really get me started with VBScript?
I guess I need to have a good knowledge of the objects and properties concepts.
You can create a temp file, then rename it back to original file:
Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = "c:\test\file.txt"
strTemp = "c:\test\temp.txt"
Set objFile = objFS.GetFile(strFile)
Set objOutFile = objFS.CreateTextFile(strTemp,True)
Set ts = objFile.OpenAsTextStream(1,-2)
Do Until ts.AtEndOfStream
strLine = ts.ReadLine
' do something with strLine
objOutFile.Write(strLine)
Loop
objOutFile.Close
ts.Close
objFS.DeleteFile(strFile)
objFS.MoveFile strTemp,strFile
Usage is almost the same using OpenTextFile:
Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = "c:\test\file.txt"
strTemp = "c:\test\temp.txt"
Set objFile = objFS.OpenTextFile(strFile)
Set objOutFile = objFS.CreateTextFile(strTemp,True)
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
' do something with strLine
objOutFile.Write(strLine & "kndfffffff")
Loop
objOutFile.Close
objFile.Close
objFS.DeleteFile(strFile)
objFS.MoveFile strTemp,strFile
Find more about the FileSystemObject object at http://msdn.microsoft.com/en-us/library/aa242706(v=vs.60).aspx. For good VBScript, I recommend:
Option Explicit to help detect typos in variables.
Function and Sub to improve readilbity and reuse
Const so that well known constants are given names
Here's some code to read and write text to a text file:
Option Explicit
Const fsoForReading = 1
Const fsoForWriting = 2
Function LoadStringFromFile(filename)
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename, fsoForReading)
LoadStringFromFile = f.ReadAll
f.Close
End Function
Sub SaveStringToFile(filename, text)
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename, fsoForWriting)
f.Write text
f.Close
End Sub
SaveStringToFile "f.txt", "Hello World" & vbCrLf
MsgBox LoadStringFromFile("f.txt")
You could open two textstreams, one for reading
Set filestreamIn = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Test.txt,1)
and one for appending
Set filestreamOUT = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Test.txt,8,true)
The filestreamIN can read from the begining of the file, and the filestreamOUT can write to the end of the file.
Don't think so...you can only use openTextFile for reading (1), writing (2), or appending (8). Reference here.
If you were using VB6 instead of VBScript, you could do:
Open "Filename" [For Mode] [AccessRestriction] [LockType] As #FileNumber
Using the Random mode. For example:
Open "C:\New\maddy.txt" For Random As #1
You could put it in an Excel sheet, idk if it'll be worth it for you if its needed for other things but storing info in excel sheets is a lot nicer because you can easily read and write at the same time with the
'this gives you an excel app
oExcel = CreateObject("Excel.Application")
'this opens a work book of your choice, just set "Target" to a filepath
oBook = oExcel.Workbooks.Open(Target)
'how to read
set readVar = oExcel.Cell(1,1).value
'how to write
oExcel.Cell(1,2).value = writeVar
'Saves & Closes Book then ends excel
oBook.Save
oBook.Close
oExcel.Quit
sorry if this answer isnt helpful, first time writing an answer and just thought this might be a nicer way for you
You could also read the entire file in, and store it in an array
Set filestreamIN = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Test.txt",1)
file = Split(filestreamIN.ReadAll(), vbCrLf)
filestreamIN.Close()
Set filestreamIN = Nothing
Manipulate the array in any way you choose, and then write the array back to the file.
Set filestreamOUT = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Test.txt",2,true)
for i = LBound(file) to UBound(file)
filestreamOUT.WriteLine(file(i))
Next
filestreamOUT.Close()
Set filestreamOUT = Nothing
Regardless of what you're trying to do there should be no need to read to and write to a file at the same time. It would also use more memory which should always be avoided. I'd suggest reading the entire file using the .ReadAll method and then close it and do whatever you need to do with the data (assuming you read the contents into a variable) and then do a write to the same file and overwrite the file. If you're concerned with having something go wrong when over-writing the current file you could always try to write it to a different file and throw an error if that doesn't work before trying to over-write the original.
Below is some simple code to execute this:
sLocation = "D:\Excel-Fso.xls"
sTxtLocation = "D:\Excel-Fso.txt"
Set ObjExl = CreateObject("Excel.Application")
Set ObjWrkBk = ObjExl.Workbooks.Open(sLocation)
Set ObjWrkSht = ObjWrkBk.workSheets("Sheet1")
ObjExl.Visible = True
Set FSO = CreateObject("Scripting.FileSystemObject")
Set FSOFile = FSO.CreateTextFile (sTxtLocation)
sRowCnt = ObjWrkSht.usedRange.Rows.Count
sColCnt = ObjWrkSht.usedRange.Columns.Count
For iLoop = 1 to sRowCnt
For jLoop = 1 to sColCnt
FSOFile.Write(ObjExl.Cells(iLoop,jLoop).value) & vbtab
Next
Next
Set ObjWrkBk = Nothing
Set ObjWrkSht = Nothing
Set ObjExl = Nothing
Set FSO = Nothing
Set FSOFile = Nothing
This is for create a text file
For i = 1 to 10
createFile( i )
Next
Public Sub createFile(a)
Dim fso,MyFile
filePath = "C:\file_name" & a & ".txt"
Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile = fso.CreateTextFile(filePath)
MyFile.WriteLine("This is a separate file")
MyFile.close
End Sub
And this for read a text file
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Set dict = CreateObject("Scripting.Dictionary")
Set file = fso.OpenTextFile ("test.txt", 1)
row = 0
Do Until file.AtEndOfStream
line = file.Readline
dict.Add row, line
row = row + 1
Loop
file.Close
For Each line in dict.Items
WScript.Echo line
WScript.Sleep 1000
Next

Resources