How to Create a File in VBScript
- 1). Right-click in Windows Explorer, select "New" from the pop-up menu and then click on the "Text Document" menu item to create a text file.
- 2). Open the newly created file for editing. This will be the container for all of the VBScript code you write. In each step below, you will see several lines of code with a plain English description of what they do. When you put all of these lines of code together, you end up with a script to create a text file.
- 3). Create a variable for the file system object and instantiate it (set it to a new instance of the object). In VBScript you create variables by "dimensioning" them with the "Dim" command. Complex variables (ones that aren't strings, integers or booleans) have to be instantiated before you can use them.
Copy the following code into your text file:
Dim objFSO 'As FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject") - 4). Add a string variable for the directory path where you want to put the file and set it to the desired location.
Copy the following code into your text file:
Dim strDirectory 'As String
strDirectory = "C:\NewDirectory" - 5). Make sure that the directory folder exists. If the directory is not there, then create it using the file system object.
Copy the following code into your text file:
Dim objDirectory 'As Object
If objFSO.FolderExists(strDirectory) Then
Set objDirectory = objFSO.GetFolder(strDirectory)
Else
Set objDirectory = objFSO.CreateFolder(strDirectory)
End If - 6). Make a string variable for the file name and set it to an appropriate value.
Copy the following code into your text file:
Dim strFile 'As String
strFile = "NewFile.txt" - 7). Create a variable for the text file and instantiate it. The CreateTextFile method has an optional parameter for overwriting the file it it already exists.
Copy the following code into your text file:
Dim objTextFile 'As Object
Dim blnOverwrite 'As Boolean
blnOverwrite = True
Set objTextFile = objFSO.CreateTextFile(strDirectory & "\" & strFile, blnOverwrite) - 8). Write data to the newly created file with the code below. There are two methods for writing to files, "Write" and "WriteLine." The latter method automatically includes a new line character for you, whereas the former just appends data to what is already present.
Copy the following code into your text file:
objTextFile.Write("This is ")
objTextFile.WriteLine("a new text file")
' This results in the string "This is a new text file" - 9). Close the file with code and properly release all objects.
Copy the following code into your text file:
objTextFile.Close
Set objTextFile = Nothing
Set objDirectory = Nothing
Set objFSO = Nothing - 10
Save all of the code you created in the previous steps into the text file at the beginning and then close the file. Rename the file with ".vbs" instead of ".txt" by right-clicking on the file and selecting "Rename" from the pop-up menu. Double-click on the file to execute the code.