Creating and writing lines to a file
Is it possible to create a file and write lines to it in vbscript?
Something similar to echo in bat file (echo something something >>sometextfile.txt
).
On execution of the vbscript depending on the path of the script would create an autorun.inf file to execute a particular program (\smartdriverbackup\sdb.exe).
Also how can I strip/remove the drive letter from the complete file path?
Solution 1:
Set objFSO=CreateObject("Scripting.FileSystemObject")
' How to write file
outFile="c:\test\autorun.inf"
Set objFile = objFSO.CreateTextFile(outFile,True)
objFile.Write "test string" & vbCrLf
objFile.Close
'How to read a file
strFile = "c:\test\file"
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
strLine= objFile.ReadLine
Wscript.Echo strLine
Loop
objFile.Close
'to get file path without drive letter, assuming drive letters are c:, d:, etc
strFile="c:\test\file"
s = Split(strFile,":")
WScript.Echo s(1)
Solution 2:
You'll need to deal with File System Object
. See this OpenTextFile
method sample.
Solution 3:
' Create The Object
Set FSO = CreateObject("Scripting.FileSystemObject")
' How To Write To A File
Set File = FSO.CreateTextFile("C:\foo\bar.txt",True)
File.Write "Example String"
File.Close
' How To Read From A File
Set File = FSO.OpenTextFile("C:\foo\bar.txt")
Do Until File.AtEndOfStream
Line = File.ReadLine
WScript.Echo(Line)
Loop
File.Close
' Another Method For Reading From A File
Set File = FSO.OpenTextFile("C:\foo\bar.txt")
Set Text = File.ReadAll
WScript.Echo(Text)
File.Close