Load all files within a folder into an array with vbscript / hta? - arrays

I want to load all files of a directory into an array with vbscipt/hta in order to sort and "call" them later by index. I've tried something like this, but it's not working:
Set objFSO = CreateObject("Scripting.FileSystemObject")
objFileFolder = "C:\"
Set objFolder = objFSO.GetFolder(objFileFolder)
Set colFiles = objFolder.Files
dim arrFileList()
For Each objFile in colFiles
ReDim Preserve arrFileList(UBound(arrFileList) + 1)
FileList(UBound(arrFileList)) = objFile.Name
Next
I'd be grateful for any help! THX in advance

You need to change two things, please see new code below. Comments in line.
Set objFSO = CreateObject("Scripting.FileSystemObject")
objFileFolder = "C:\"
Set objFolder = objFSO.GetFolder(objFileFolder)
Set colFiles = objFolder.Files
dim arrFileList()
ReDim Preserve arrFileList(0) 'If you wish to use the array UBound later on you must redim this here
For Each objFile in colFiles
ReDim Preserve arrFileList(UBound(arrFileList) + 1)
arrFileList(UBound(arrFileList)) = objFile.Name ' Here you were calling FileList, not arrFileList
Next
You could further tidy / improve this code as arrFileList(0) will have no value upon finishing.

Related

VBscript create array but omit blank variables

I am looking to create a script that will compare the last modified date of up to 4 files then capture the one most recently modified. My current road block is that some files might not exist.
The set will fail if the file does not exist but I can easily overcome that by looking for the file and if it does not exist simply skip the set command. This would cause the creation of the array to fail because my variable is now blank.
Any suggestions how to resolve this?
Here is what I have so far:
Option Explicit
Dim objFSO, path, file, recentDate, recentFile, File1, File2, File3, File4, afiles, File1date, date1
Set objFSO = CreateObject("Scripting.FileSystemObject")
set File1=objFSO.getfile("c:\temp\file.txt")
set File2=objFSO.getfile("c:\test\File.txt")
set File3=objFSO.getfile("c:\users\%profile%\documents\File.txt")
set File4=objFSO.getfile("c:\users\public\documents\File.txt")
'Prepare variables to store the required information
Dim dateMin, dateMax
date1 = File1.datelastmodified
wscript.echo date1
wscript.echo now
dateMin = date1
dateMax = date1
afiles = Array( File1.datelastmodified, File2.datelastmodified, File3.datelastmodified, File4.datelastmodified )
Dim i
For i=1 to UBound(aFiles)
If aFiles(i) < dateMin Then dateMin = aFiles(i)
if aFiles(i) > dateMax Then dateMax = aFiles(i)
Next
'
' Output Information
WScript.Echo "Highest: " & CStr( dateMax )
WScript.Echo " Lowest: " & CStr( dateMin )
I think this would be much easier if you use an ArrayList to capture the DateLastModified for each file.
An ArrayList lets you dynamically add values unlike a VBScript Array.
Furthermore, the ArrayList has a very useful method called Sort() we can use here to determine the dateMin and dateMax values.
Try:
Option Explicit
Dim objFSO, objList, objFile, arrFiles, fileName
arrFiles = Array("c:\temp\file.txt","c:\test\File.txt","c:\users\%profile%\documents\File.txt","c:\users\public\documents\File.txt")
Set objList = CreateObject("System.Collections.ArrayList")
Set objFSO = CreateObject("Scripting.FilesystemObject")
For Each fileName In arrFiles
If objFSO.FileExists(fileName) Then
Set objFile = objFSO.GetFile(fileName)
objList.Add objFile.DateLastModified
End If
Next
objList.Sort()
' Prepare variables to store the required information
Dim dateMin, dateMax
dateMin = objList.item(0)
dateMax = objList.item(objList.Count - 1)
' Output Information
WScript.Echo "Highest: " & CStr( dateMax )
WScript.Echo "Lowest: " & CStr( dateMin )
' Clean up
Set objFSO = Nothing
Set objFile = Nothing
Set objList = Nothing
Edit
The above code was a remake of your original code. I may have misunderstood then that your goal is to find the file most recently modified.
This should do what you have in mind:
Option Explicit
Dim objFSO, objFile, objLatest, fileName, arrFiles
arrFiles = Array("c:\temp\file.txt","c:\test\File.txt","c:\users\%profile%\documents\File.txt","c:\users\public\documents\File.txt")
Set objFSO = CreateObject("Scripting.FilesystemObject")
Set objLatest = Nothing
For Each fileName In arrFiles
If objFSO.FileExists(fileName) Then
Set objFile = objFSO.GetFile(fileName)
If (objLatest Is Nothing) Then
Set objLatest = objFile
ElseIf (objFile.DateLastModified > objLatest.DateLastModified) Then
Set objLatest = objFile
End If
End If
Next
If objLatest Is Nothing Then
WScript.Echo "None of the files in 'arrFiles' exist.."
Else
' Here you decide if you want to keep the latest file as Object (-> objLatest) or just as a string to the full pathname of that file
Dim latestFile
latestFile = objFSO.GetAbsolutePathName(objLatest) ' store the full path and filename
' Info on FormatDateTime() at https://www.w3schools.com/asp/func_formatdatetime.asp
WScript.Echo "Most recently modified file is '" & latestFile & "' at " & FormatDateTime(objLatest.DateLastModified, 0)
End If
' Clean up
Set objFSO = Nothing
Set objFile = Nothing
Set objLatest = Nothing

vbs file search for extention in a directory

I'm trying to write this code in VBs, (I'm quite new)
I want to have the code go through a folder/directory, and pick out all ".txt" files, in something like a for loop. These text files could then be listed using MsgBox ("txt filename"). This is what I've got so far:
Set objFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = "C:\Users\Desktop\folder"
Set objFolder = objFSO.GetFolder(objStartFolder)
Set colFiles = objFolder.Files
For Each objFile in colFiles
If UCase(objFSO.GetExtensionName(objFile.name)) = ".txt" Then
Wscript.Echo objFile.Name
Next
It doesn't seem to be picking out a txt file called "name.txt". Any help would be greatly appreciated.
ps:
please ignore and bad spelling and my terrible formatting (im new to stackoverflow) Thanks! (also the code above is mostly mashed together code i found off the internet)
You should modify this line ; if you use UCase :
If UCase(objFSO.GetExtensionName(objFile.name)) = ".txt"
To
If UCase(objFSO.GetExtensionName(objFile)) = "TXT"
Or if you use LCase
If LCase(objFSO.GetExtensionName(objFile)) = "txt"
And your code looks like this one :
Set objFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = "C:\Users\Desktop\folder"
Set objFolder = objFSO.GetFolder(objStartFolder)
Set colFiles = objFolder.Files
For Each objFile in colFiles
If LCase(objFSO.GetExtensionName(objFile)) = "txt" Then
Wscript.Echo objFile.Name
End If
Next
GetExtensionName Method

Copy ONLY recent by DateLastModified file over VbScript

New at VbScript so please include all lines if you can.
I have
Source-folder C:\s\ with files with names et_v01.txt, et_v02.txt etc. Destination-folder C:\d\ I only want the latest file to be COPIED from S to D which would be et_v02 since we'll use DateLastModified.
Bonus at destination only keep the latest file if it runs next time when a new version comes in. Thanks in advance and I have searched for this but the others had less than criteria and etc.
Option Explicit
Dim objFSO : Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim objSTR, objEND, objTYP, objEXT, objKEY, objFILE
Dim Folder, SubFolder
objSTR = "C:\s\"
objEND = "C:\d\"
For Each objFILE in objFSO.GetFolder(objSTR).Files
If objFILE.DateLastModified > DateAdd("d",-4,now) then
objFILE.Copy objEND
End If
Next
Here try this version:
Option Explicit
Dim objFSO : Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim strSource, strDestination
strSource = "C:\s\"
strDestination = "C:\d\"
Dim objFile, objOldestFileSoFar
For Each objFile in objFSO.GetFolder(strSource).Files
If Not IsEmpty(objOldestFileSoFar) Then
If objFile.DateLastModified > objOldestFileSoFar.DateLastModified Then
Set objOldestFileSoFar = objFile
End If
Else 'This is the first loop, i.e. we have no previous "last mod" to compare against.
Set objOldestFileSoFar = objFile
End If
Next
objOldestFileSoFar.Copy strDestination
Also, I've cleaned up your code a bit to get rid of unused declarations and to apply better naming to your variables. Take those as suggestions if you like, but just keep in mind that adhering to conventions is important.

Creating a VBS file with the ability to write out to a text file

I have a VBS file that I am trying to use to determine what folders and files are in a certain directory. I believe I have the code written correctly, but whenever I try to write out the file or current directory I get a blank text document with nothing but the root directory written out. Any advice would be greatly appreciated.
Dim NewFile
Function GetFolders (strFolderPath)
Dim objCurrentFolder, colSubfolders, objFolder, files
Set objCurrentFolder = objFSO.GetFolder(strFolderPath)
Set colSubfolders = objCurrentFolder.SubFolders
For Each objFolder In colSubfolders
NewFile.WriteLine(" - " & objFolder.Path)
Set files = folder.Files
For each folderIdx In files
NewFile.WriteLine(" - "& folderIdx.Name)
Next
Call GetFolders (objFolder.Path)
Next
End Function
Dim fso, sFolder
Set fso = CreateObject("Scripting.FileSystemObject")
sFolder = Wscript.Arguments.Item(0)
If sFolder = "" Then
Wscript.Echo "No Folder parameter was passed"
Wscript.Quit
End If
Set NewFile = fso.CreateTextFile(sFolder&"\FileList.txt", True)
NewFile.WriteLine(sFolder)
Call GetFolders(sFolder)
NewFile.Close
You haven't payed sufficient attention to your variable naming. Your script is a good example of the reason why all VBScripts should start with the line:-
Option Explicit
This would highlight all the variables that haven't been declared which in turn will point out typos and inconsistencies in variable naming. Here is how I would write it:-
Option Explicit
Dim msFolder : msFolder = Wscript.Arguments.Item(0)
If msFolder = "" Then
Wscript.Echo "No Folder parameter was passed"
Wscript.Quit
End If
Dim mfso : Set mfso = CreateObject("Scripting.FileSystemObject")
Dim moTextStream : Set moTextStream = mfso.CreateTextFile(msFolder & "\FileList.txt", True)
moTextStream.WriteLine(msFolder)
WriteFolders mfso.GetFolder(msFolder)
moTextStream.Close
Sub WriteFolders(oParentFolder)
Dim oFolder
For Each oFolder In oParentFolder.SubFolders
moTextStream.WriteLine(" - " & oFolder.Path)
Dim oFile
For Each oFile In oFolder.Files
moTextStream.WriteLine(" - " & oFile.Name)
Next
WriteFolders oFolder
Next
End Sub

How to make a batch file edit a text file

I got the code
Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = "C:\test\file.txt"
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
If InStr(strLine,"ex3")> 0 Then
strLine = Replace(strLine,"ex3","ex5")
End If
WScript.Echo strLine
Loop
The strLine replacing part i can fix myself to use with my own purposes, but how do i do something like this so that it doesn't require the file's name, it just edits all text files within the document?
you can do it like this,
strFolder = "c:\myfolder"
Set objFolder = objFS.GetFolder(strFolder)
For Each strFile In objFolder.Files
strFileName =strFile.Name
strFilePath = strFile.Path
strFileExt = objFS.GetExtensionName(strFile)
If strFileExt = "txt" Then
Set objFile = objFS.OpenTextFile(strFile)
' your current code here..
objFile.Close()
End If
Next

Resources