Creating and writing lines to a file

Vbscript

Vbscript Problem Overview


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?

Vbscript Solutions


Solution 1 - Vbscript

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 - Vbscript

You'll need to deal with File System Object. See this OpenTextFile method sample.

Solution 3 - Vbscript

' 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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDario DiasView Question on Stackoverflow
Solution 1 - Vbscriptghostdog74View Answer on Stackoverflow
Solution 2 - VbscriptRubens FariasView Answer on Stackoverflow
Solution 3 - VbscriptTheRealSuicuneView Answer on Stackoverflow