Visual Basic Script - Listing Files
Author: jason
Date: 2004-05-29
Category: Technical

Here's a quick introduction into getting a file listing from VBScript. VBScript is a great way to do little tasks in Windows. This should work on W2K and XP.

What we will do:
1. Get information about each file
2. Write the info to a text file

Here's the full code (list.vbs)
Code

Dim FileSys, WrLine, oFile
Set FileSys = CreateObject("Scripting.FileSystemObject")
Set WrLine = FileSys.CreateTextFile("c:\files.txt", True)
For Each oFile In FileSys.GetFolder("c:\").Files
WrLine.WriteLine (oFile.Name & vbTab & oFile.DateCreated & vbTab & oFile.DateLastModified & vbTab & oFile.DateLastAccessed)
Next
WrLine.Close


Now lets step through the code

Here we set up our variables. "FileSys" will hold the file system object. "WrLine" writes into our text file. "oFile" will hold the actual file info.
Code

Dim FileSys, WrLine, oFile


We set our variable "FileSys" to create the file system object. We set "WrLine" to create a text file with the "FileSys" object we just made. "WrLine" will write our info on the c: to the text file. The "true" tells the system its okay to overwrite the file, if it already exists
Code

Set FileSys = CreateObject("Scripting.FileSystemObject")
Set WrLine = FileSys.CreateTextFile("c:\files.txt", True)


Now we want to open the directory up and read the files, one at a time. "oFile" is each file in the folder c:\. We use the file system object from "FileSys" to get the files within the folder.
Code

For Each oFile In FileSys.GetFolder("c:\").Files


Write their info onto a line in the text file. "oFile.Name" is the name of the file within the folder we are looking. The "& vbTab &" tells VBScript to listen after which piece of info, add the tab, and listen for another piece of info. We start it with a "(" and end with a ")".
Code

WrLine.WriteLine (oFile.Name & vbTab & oFile.DateCreated & vbTab & oFile.DateLastModified & vbTab & oFile.DateLastAccessed)


We step through each file
Code

Next


Close up the text file, we're done
Code

WrLine.Close


This is a very simple script. It doesn't read subfolders. It doesn't filter out certain file types. And it makes an ugly text file. Later I'll show how to search for a specified file type. Look in subfolders. And make an HTML page with the results.

Reference: http://www.scit.wlv.ac.uk/appdocs/chili-asp/html/vbscript_language_reference.htm



jason @ jasonthomasfrance.com - www.masterstationlog.com - copyright 2009