First, we tell objFile that we want a TextFile, (as opposed to an Excel spreadsheet). Once we have our TextFile we can apply the WriteLine method and populate the file with a text string. In truth this is a little laborious, and the main use of FSO is to read data that is already in the text file, (or spreadsheet). Finally we clear the memory buffers and save the file with .Close method.
‘VBScript to demonstrate creating a file
‘ Guy Thomas January 2004
Dim objFile, strGuyFile, strFilePath
strFilePath = "e:\files\strGuyFile.txt"
Set objFile = CreateObject("Scripting.FileSystemObject")
Set strGuyFile = objFile.CreateTextFile(strFilePath, True)
strGuyFile.WriteLine("This was made using VBScript.")
The scenario is that you have hundreds of usernames in a spreadsheet. You wish to create a script that can read those values. Your long term goal it to write the usernames into Active Directory.
If you wish to try the script below, either write your own spreadsheet, or download one I made earlier from here: GuyUsers.xls.
Important, to get the script to work, save the file to C:\Scripts\GuyUsers.xls, or alter the path statement in line 7.
‘To open a Spreadsheet. Read a value from the 1st column, 3rd row
Dim objExcel, strPathExcel,strCN
Dim objFile, strGuyFile, intRow
intRow = 3
Set objExcel = CreateObject("Excel.Application")
strPathExcel = "e:\files\GuyUsers.xls"
Set objSheet = objExcel.ActiveWorkbook.Worksheets(1)
strCN = Trim(objSheet.Cells(intRow, 1).Value)
Note 1: On Line 6, CreateObject method produces an Excel application not a TextFile.
Note 2: Because we are dealing with a spreadsheet, we need to make sure we are reading the correct Worksheet.
Note 3: On Line 10 .Cells(intRow, 1) means the third row because intRow = 3 and 1 refers to the column offset.
Guy Recommends: WMI Monitor and It’s Free!
Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft’s operating systems. Fortunately, SolarWinds have created a Free WMI Monitor so that you can discover these gems of performance information, and thus improve your scripts.
Take the guess work out of which WMI counters to use when scripting the operating system, Active Directory or Exchange Server. Give this WMI monitor a try – it’s free.
Download your free copy of WMI Monitor
• (Part 1) VBScript to Create Folders • (Part 2) VBScript to Create Files