Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Visual Basic [VB] (http://www.go4expert.com/articles/visual-basic-tutorials/)
-   -   List All Files in Folder using VBScript (http://www.go4expert.com/articles/list-files-folder-using-vbscript-t927/)

pradeep 24Jun2006 14:10

List All Files in Folder using VBScript
 
Sometimes you might require to get a list of all the files in a folder, I was thinking how it can be implemented, the solution is to used the WSH interface and write a script in VBScript.
Below is a sample script which will get the list of files on a directory, say c:\windows and save it to the file c:\windows\FileList.txt.

Code: VB

On Error Resume Next
  Dim fso, folder, files, NewsFile,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)
  Set folder = fso.GetFolder(sFolder)
  Set files = folder.Files
 
  For each folderIdx In files
    NewFile.WriteLine(folderIdx.Name)
  Next
  NewFile.Close


Example usage:
Code:

lister.vbs "c:\documents and settings"

More VB Articles



VB.Net Array Basics
Variables in Visual Basic
Strings in VB - Part I
Binary Conversion In VB
VB6 Small Backup Program

htl 21Mar2007 17:34

Re: List All Files in Folder using VBScript
 
hi,
very nice
a wonderful example code

htl.

azrul 20Jan2009 06:51

Re: List All Files in Folder using VBScript
 
Hey, i would like to enchance it by providing a dialog box. However, i failed to make it work. Care to point me on the right direction?


Quote:


On Error Resume Next
Dim fso, folder, files, NewFile, sfolder, path

path = InputBox ("Please write your path")
sFolder = "& path &"

Set fso = CreateObject("Scripting.FileSystemObject")
If sFolder = null Then
Wscript.Echo "No Folder parameter was passed"
Wscript.Quit
End If

Set NewFile = fso.CreateTextFile(sFolder&"\Filelist.txt", True)
Set folder = fso.GetFolder(sFolder)
Set files = folder.Files
For each folderIdx In files
NewFile.WriteLine(folderIdx.Name)
Next
NewFile.close


Cyprian Wyatt 30Jan2009 21:00

Re: List All Files in Folder using VBScript
 
Code:

On Error Resume Next

Const WINDOW_HANDLE = 0
Const BIF_EDITBOX = &H10
Const BIF_NONEWFOLDER = &H0200
Const BIF_RETURNONLYFSDIRS = &H1

Set objShell = CreateObject("Shell.Application")
Set wshShell = CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")

'**Browse For Folder To Be Processed
strPrompt = "Please select the folder to process."
intOptions = BIF_RETURNONLYFSDIRS + BIF_NONEWFOLDER + BIF_EDITBOX
strTargetPath = wshShell.SpecialFolders("MyDocuments")
strFolderPath = Browse4Folder(strPrompt, intOptions, strTargetPath)

Set objNewFile = objFSO.CreateTextFile(strFolderPath & "\filelist.txt", True)
Set objFolder = objFSO.GetFolder(strFolderPath)
Set objColFiles = objFolder.Files

For Each file In objColFiles
        objNewFile.WriteLine(file.Name)
Next
objNewFile.Close

'**Browse4Folder Function
Function Browse4Folder(strPrompt, intOptions, strRoot)
        Dim objFolder, objFolderItem

        On Error Resume Next

        Set objFolder = objShell.BrowseForFolder(0, strPrompt, intOptions, strRoot)
          If (objFolder Is Nothing) Then
                  Wscript.Quit
        End If
          Set objFolderItem = objFolder.Self
          Browse4Folder = objFolderItem.Path
          Set objFolderItem = Nothing
          Set objFolder = Nothing
End Function

Here ya go. I would change the createtext file to another location, such as to 'c:\'. You can also change the strTargetPath to any valid path.

stasis 26Feb2009 05:50

Re: List All Files in Folder using VBScript
 
So how could you modify this to list all sub directories inside the folder you choose?

SaswatPadhi 8May2009 17:52

Re: List All Files in Folder using VBScript
 
Quote:

Originally Posted by stasis (Post 43509)
So how could you modify this to list all sub directories inside the folder you choose?

It's really simple ! You just need to check <folder>.folders instead of <folder>.files.
Code: vb

On Error Resume Next

Const WINDOW_HANDLE = 0
Const BIF_EDITBOX = &H10
Const BIF_NONEWFOLDER = &H0200
Const BIF_RETURNONLYFSDIRS = &H1

Set objShell = CreateObject("Shell.Application")
Set wshShell = CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")

'**Browse For Folder To Be Processed
strPrompt = "Please select the folder to process."
intOptions = BIF_RETURNONLYFSDIRS + BIF_NONEWFOLDER + BIF_EDITBOX
strTargetPath = wshShell.SpecialFolders("MyDocuments")
strFolderPath = Browse4Folder(strPrompt, intOptions, strTargetPath)

Set objNewFile = objFSO.CreateTextFile(strFolderPath & "\filelist.txt", True)
Set objFolder = objFSO.GetFolder(strFolderPath)
' CHANGE STARTS HERE :
Set objColFolders = objFolder.Folders

For Each tfolder In objColFolders
    objNewFile.WriteLine(tfolder.Name)
Next
' CHANGE DONE.
objNewFile.Close

'**Browse4Folder Function
Function Browse4Folder(strPrompt, intOptions, strRoot)
    Dim objFolder, objFolderItem

    On Error Resume Next

    Set objFolder = objShell.BrowseForFolder(0, strPrompt, intOptions, strRoot)
    If (objFolder Is Nothing) Then
      Wscript.Quit
    End If
    Set objFolderItem = objFolder.Self
    Browse4Folder = objFolderItem.Path
    Set objFolderItem = Nothing
    Set objFolder = Nothing
End Function


seomaster 9May2009 16:19

Re: List All Files in Folder using VBScript
 
HI

hi,
very nice
a wonderful example code and i thank u really great.........


Staffing service

Seo master

SaswatPadhi 9May2009 16:27

Re: List All Files in Folder using VBScript
 
You are welcome ! :smile:

ttran4 21May2009 10:42

Re: List All Files in Folder using VBScript
 
This is definitley a great example.

How can it be modified to list files in the main directory and any subdirectories? I'd like to write something that will give me the name, create date, modify date for all files in the main directory and for any files in the sub-directories.

I wrote the following, but it can not handle sub-directories. Any help is appreciated. Thanks.



On Error Resume Next
Dim fso, folder, files, NewsFile,sFolder
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder("C:\Documents and Settings\Phat Buddha\desktop\")
Set outfile = fso.CreateTextFile("c:\temp\testout.txt")
Set files = folder.Files


For each folderIdx In files
outfile.WriteLine(folderIdx.Name & ";" & folderIdx.DateCreated & ";" & folderIdx.DateLastModified)
Next
outfile.Close

Yukta 18Jun2009 02:11

Re: List All Files in Folder using VBScript
 
Hi:
I am a novice to VBS. I was wodering if it is possible to read thru the files in a folder and capture the last line in every file(csv file) and write to a logfile that has the name(with date and time)
Also, is it possible that when capturing the last line , I have to extract the last field value compare it with a base value and if it is greater than the base value then write it the log file. Since it loops thru each file in the folder, base values for each file keep changing. I am not quite sure how to do it. Any help would be great.
Thanks,
Yukta.

eLn1r0 11Sep2009 15:30

Re: List All Files in Folder using VBScript
 
Hallo

This is what i was surching for a very long time. But i must filter the files i want listed in the .txt file by the extension of the files.. could someone help me?

pascalsk 12Sep2009 01:59

Re: List All Files in Folder using VBScript
 
Dis is great Keep it up. i hope to learn more from u.

chmod777 24Sep2009 19:22

Re: List All Files in Folder using VBScript
 
Quote:

Originally Posted by SaswatPadhi (Post 47411)
It's really simple ! You just need to check <folder>.folders instead of <folder>.files.
Code: vb
On Error Resume Next

Const WINDOW_HANDLE = 0
Const BIF_EDITBOX = &H10
Const BIF_NONEWFOLDER = &H0200
Const BIF_RETURNONLYFSDIRS = &H1

Set objShell = CreateObject("Shell.Application")
Set wshShell = CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")

'**Browse For Folder To Be Processed
strPrompt = "Please select the folder to process."
intOptions = BIF_RETURNONLYFSDIRS + BIF_NONEWFOLDER + BIF_EDITBOX
strTargetPath = wshShell.SpecialFolders("MyDocuments")
strFolderPath = Browse4Folder(strPrompt, intOptions, strTargetPath)

Set objNewFile = objFSO.CreateTextFile(strFolderPath & "\filelist.txt", True)
Set objFolder = objFSO.GetFolder(strFolderPath)
' CHANGE STARTS HERE :
Set objColFolders = objFolder.Folders

For Each tfolder In objColFolders
&nbsp;&nbsp;&nbsp;&nbsp;objNewFile.WriteLine(tfolder.Name)
Next
' CHANGE DONE.
objNewFile.Close

'**Browse4Folder Function
Function Browse4Folder(strPrompt, intOptions, strRoot)
&nbsp;&nbsp;&nbsp;&nbsp;Dim objFolder, objFolderItem

&nbsp;&nbsp;&nbsp;&nbsp;On Error Resume Next

&nbsp;&nbsp;&nbsp;&nbsp;Set objFolder = objShell.BrowseForFolder(0, strPrompt, intOptions, strRoot)
&nbsp;&nbsp;&nbsp;&nbsp;If (objFolder Is Nothing) Then
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Ws cript.Quit
&nbsp;&nbsp;&nbsp;&nbsp;End If
&nbsp;&nbsp;&nbsp;&nbsp;Set objFolderItem = objFolder.Self
&nbsp;&nbsp;&nbsp;&nbsp;Browse4Folder = objFolderItem.Path
&nbsp;&nbsp;&nbsp;&nbsp;Set objFolderItem = Nothing
&nbsp;&nbsp;&nbsp;&nbsp;Set objFolder = Nothing
End Function

I have tried this in both Windows Vista, and again on XP (thinking that maybe Vista had issues), and I cannot get this to read the folders. It just creates an empty 'filelist.txt' file. I have not modified this script in any way, and have tried diff. folders. Any suggestions from anyone?

SaswatPadhi 24Sep2009 19:37

Re: List All Files in Folder using VBScript
 
Quote:

Originally Posted by chmod777 (Post 57911)
I have tried this in both Windows Vista, and again on XP (thinking that maybe Vista had issues), and I cannot get this to read the folders. It just creates an empty 'filelist.txt' file. I have not modified this script in any way, and have tried diff. folders. Any suggestions from anyone?

Hi,

Thanx for reporting. :)

There was a typo at this line :Set objColFolders = objFolder.Folders
It should read :Set objColFolders = objFolder.SubFolders.

Correct code [ TESTED ] is :
Code: VB

On Error Resume Next

Const WINDOW_HANDLE = 0
Const BIF_EDITBOX = &H10
Const BIF_NONEWFOLDER = &H0200
Const BIF_RETURNONLYFSDIRS = &H1

Set objShell = CreateObject("Shell.Application")
Set wshShell = CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")

'**Browse For Folder To Be Processed
strPrompt = "Please select the folder to process."
intOptions = BIF_RETURNONLYFSDIRS + BIF_NONEWFOLDER + BIF_EDITBOX
strTargetPath = wshShell.SpecialFolders("MyComputer")
strFolderPath = Browse4Folder(strPrompt, intOptions, strTargetPath)

Set objNewFile = objFSO.CreateTextFile(strFolderPath & "\filelist.txt", True)
Set objFolder = objFSO.GetFolder(strFolderPath)
' CHANGE STARTS HERE :
Set objColFolders = objFolder.SubFolders

For Each tfolder In objColFolders
    objNewFile.WriteLine(tfolder.Name)
Next
' CHANGE DONE.
objNewFile.Close

'**Browse4Folder Function
Function Browse4Folder(strPrompt, intOptions, strRoot)
    Dim objFolder, objFolderItem

    On Error Resume Next

    Set objFolder = objShell.BrowseForFolder(0, strPrompt, intOptions, strRoot)
    If (objFolder Is Nothing) Then
      Wscript.Quit
    End If
    Set objFolderItem = objFolder.Self
    Browse4Folder = objFolderItem.Path
    Set objFolderItem = Nothing
    Set objFolder = Nothing
End Function


chmod777 24Sep2009 19:55

Re: List All Files in Folder using VBScript
 
Well that did the trick. Thanks.

SaswatPadhi 24Sep2009 20:03

Re: List All Files in Folder using VBScript
 
My pleasure :)

DivinationX 13Nov2009 12:36

Re: List All Files in Folder using VBScript
 
How do i code such that, the filename that is captures will be stored into an array of strings? Thanks!

chuck42 29Jan2010 16:06

Re: List All Files in Folder using VBScript
 
Is it possible to tiune this skript, so I get a file contianing fileextention, size and owner of the file?
(I found something similar in asp: classicasp.aspfaq.com/files/directories-fso/how-do-i-find-the-owner-author-and-other-properties-of-a-file.html but I dont know how to do so in vbs or similar

hanleyhansen 29Jan2010 16:58

Re: List All Files in Folder using VBScript
 
This is very good and fairly simple. It would be nice if you explained each line for those not familiar with VB

RomuloAraujo 25Feb2010 06:45

Re: List All Files in Folder using VBScript
 
Hi here,

Very good example guys. However, I would like to push a little bit ... Let's say I have a folder containing 140k .CSVs files (avg size 5k) and I want to list them all files not to a file but to memory into an array or something... so then after listing I would be about concatenate all those files into one single big.CSV file.

is that possible?

Rom

bettlejus 12Mar2010 13:26

Re: List All Files in Folder using VBScript
 
Hello, I have the following code for sending a mail with Outlook, my problem is that I need to sedn this mail 4 times a day with a diferent file, sometimes with 2 files in attach, and I am modifying this everytime with the name of the file, not much help there

I was wondering how to tell the script to look for files in a folder and attach everything it finds to the mail

Can anyone help me?
Thanks!


Dim objOutlk
Dim objMail
Dim strMsg
Const olMailItem = 0
Set objOutlk = createobject("Outlook.Application")
Set objMail = objOutlk.createitem(olMailItem)
objMail.To = "test@company.com"
objMail.cc = ""
objMail.subject = "Subject "
strMsg = "Hello,"
objMail.Attachments.Add(c:\folder\file.txt)
objMail.body = strMsg
objMail.send
Set objMail = nothing
Set objOutlk = nothing

andorosfire 19Mar2010 21:51

Re: List All Files in Folder using VBScript
 
Does anyone know how to perform this same task on a Mac running OS X.5?

donkey 3Apr2010 15:33

Re: List All Files in Folder using VBScript
 
hi pradeep
this is a perfect useful script exmple to me, if is it possible to import any reg files in a folder like regedit /i some_files.reg instead of create filelist.txt, that I looking for, I'm very pleased do you would help me :-)
cheers
((donkey))

Jeff Greener 19Jul2010 20:04

Re: List All Files in Folder using VBScript
 
Quote:

Originally Posted by DivinationX (Post 60185)
How do i code such that, the filename that is captures will be stored into an array of strings? Thanks!

You need to declare an undimensioned array, and then initialize it at the top:
Dim myresults()
ReDim myresults(0)

then replace the output portion:
objNewFile.WriteLine(tfolder.Name)
with these two lines:

myresults(ubound(myresults))=tfolder.Name
redim Preserve Myresults(ubound(Myresults)+1)

This will leave you with an array full of the results and one empty slot at the end.

Kiru 16Aug2010 11:00

Re: List All Files in Folder using VBScript
 
Quote:

Originally Posted by chmod777 (Post 57911)
I have tried this in both Windows Vista, and again on XP (thinking that maybe Vista had issues), and I cannot get this to read the folders. It just creates an empty 'filelist.txt' file. I have not modified this script in any way, and have tried diff. folders. Any suggestions from anyone?

Hi I am Kiru. i went through these codes. Excellent.

However, i have a situation here and i would need your help in this regard.

I have a folder and i have so many sub folders. i getting the folder names in an excel file based on the last modified date.

This excel file gets updated every hour.

so, now, i want to check the current date with the last modified date.
if yes, then i have to check for the name of the folder (which is usually employees name).

I have a data base in excel file where i have fed employees name and his email address.

if a last modified date of a folder indicates a current date, i need to shoot an email to that particular person based on the database cells.

i know it is possible to write a scirpt in excel but i am not familiar with the codes.

can you help me.

edytharceo 3Sep2010 13:36

Re: List All Files in Folder using VBScript
 
This site is really great, i am glad that there is a site, thread like this. The information here is very helpful.

Bacaryu 28Sep2010 18:08

Re: List All Files in Folder using VBScript
 
Hello, I'm new to vb scripting

I need something like this code but with addition of text to the txt output file.

so the script should check for every file in the folder and give an output of :

RESTORE LOG NewDatabase
FROM DISK = ''D:\BackupFiles\TestDatabase_TransactionLogBackup1.trn'
WITH NORECOVERY

RESTORE LOG NewDatabase
FROM DISK = ''D:\BackupFiles\TestDatabase_TransactionLogBackup2.trn'
WITH NORECOVERY

Can somebody help me with that.

I don't think it should be hard to do, I only don't know how exactly.

sasaa86 15Jan2011 16:44

Re: List All Files in Folder using VBScript
 
is there a way to only save the file name and not the extension

I use it to list my mp3's

(there all the same type of files ".mp3")

Impala 20Jan2011 19:15

Re: List All Files in Folder using VBScript
 
Hi,

I get a list of folders and subfolders in the target folder.
What I like is this scrip that displays all files in the target folder and all the sub and sub sub folders also in one file output.

Thanks Roald

codvb 8Jul2011 09:13

Re: List All Files in Folder using VBScript
 
Quote:

Originally Posted by SaswatPadhi (Post 57913)
Hi,

Thanx for reporting. :)

There was a typo at this line :Set objColFolders = objFolder.Folders
It should read :Set objColFolders = objFolder.SubFolders.
...

Hi,

I adapted the code for the list folder and all sub-folders but the error below appears when I run the file:

Line: 26
Char: 5
Error: Expected statement
Code: 800A0400
Source: Microsoft VBScript compilation error


I need to list the all filenames in each folder too but, I'm beginner in VBScript! Can you help me? What I have to do?

Adapted Code:
Code:

On Error Resume Next

Const WINDOW_HANDLE = 0
Const BIF_EDITBOX = &H10
Const BIF_NONEWFOLDER = &H0200
Const BIF_RETURNONLYFSDIRS = &H1

Set objShell = CreateObject("Shell.Application")
Set wshShell = CreateObject("WScript.Shell")
Set objFSO  = CreateObject("Scripting.FileSystemObject")

strPrompt    = "Please select the folder to process."
intOptions    = BIF_RETURNONLYFSDIRS + BIF_NONEWFOLDER + BIF_EDITBOX
strTargetPath = wshShell.SpecialFolders("MyComputer")
strFolderPath = Browse4Folder(strPrompt, intOptions, strTargetPath)

Set objNewFile = objFSO.CreateTextFile(strFolderPath & "\ListaMP3.txt", True)
Set objFolder  = objFSO.GetFolder(strFolderPath)

'MY ADAPTATION START HERE
Set objColFolders = objFolder.SubFolders
:AllFolders
For Each tfolder In objColFolders
    objNewFile.WriteLine(tfolder.Name)
    objColFolders = tfolder.SubFolders
    GoTo AllFolders

Next
'END HERE

objNewFile.Close

Function Browse4Folder(strPrompt, intOptions, strRoot)
    Dim objFolder, objFolderItem

    On Error Resume Next

    Set objFolder = objShell.BrowseForFolder(0, strPrompt, intOptions, strRoot)
    If (objFolder Is Nothing) Then
      Wscript.Quit
    End If
    Set objFolderItem = objFolder.Self
    Browse4Folder = objFolderItem.Path
    Set objFolderItem = Nothing
    Set objFolder = Nothing
End Function


kaiwen21 31Jul2011 00:39

Re: List All Files in Folder using VBScript
 
Awesome script thanks

Is it possible however to split the filename into different columns in an excel table.

for e.g. the file is "001 - his name is known.mkv"

and want to split it as follows:
Column A: 001
Column B: his name is known

and drop the file extension from the file list

AutosysR11 10Apr2012 16:34

Re: List All Files in Folder using VBScript
 
Hello,

I am beginner in vbscript. Can someone help me to resolve my problem. I was trying to export all files in C:\windows with the file extension of .log and will list the file to Filelist.txt under the same path (c:\windows).


All times are GMT +5.5. The time now is 13:02.