VBScript – Create File and Create Folder

In vbscript, we can create a new textfile and directory using FileSystemObject. The FileSystemObject contains the functions CreateFolder and CreateTextFile to create file and folder. The following vbscript create the folder “TestDir” under “C:\” and create the file “Sample.txt“.

Option Explicit
Dim objFSO, objFSOText
Dim strDirectory, strFile
strDirectory = "C:\TestDir"
strFile = "Sample.txt"

' Create the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")

' Create the folder "TestDir"
 objFSO.CreateFolder(strDirectory)

' Create the file "Sample.txt"
objFSO.CreateTextFile(strDirectory & strFile)
Wscript.Echo "File created: " & strDirectory & strFile
Wscript.Quit

VBScript – Create a File and Check if a File Already Exists

Before creating new file, we need to check whether the file is already exists or not. The following vbscript check the folder “TestDir” is already exists and create the folder if not exists, and it check the file “Sample.txt” is already exists and create new file only if not exists .

Option Explicit
Dim objFSO, objFSOText
Dim strDirectory, strFile
strDirectory = "C:\TestDir"
strFile = "Sample.txt"

' Create the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")

' Check the folder "TestDir" is exists or not
If objFSO.FolderExists(strDirectory) Then
   WScript.Echo "Folder already exists : " & strDirectory
Else
   objFSO.CreateFolder(strDirectory)
   WScript.Echo "Folder created: " & strDirectory
End If

' Check the file "Sample.txt" is exists or not
If objFSO.FileExists(strDirectory & strFile) Then
      WScript.Echo "File already exists : " & strDirectory & strFile
Else
     objFSO.CreateTextFile(strDirectory & strFile)
Wscript.Echo "File created " & strDirectory & strFile
End If 
Wscript.Quit
Advertisement

Leave a Comment