Lionwit
Lionwit

Reputation: 11

I need help figuring out how to output the contexts of a TXT file in VBS

My goodness. I've searched just about everywhere for some help doing this and I can't for the love of me figure out what my issue in this code.

Set obj4 = WScript.CreateObject ("WScript.shell")
obj4.run ("cmd /c ipconfig /all > data.txt")

WScript.Sleep 3000

Set fs = CreateObject("Scripting.FileSystemObject")
Const ForReading = 1
Set fs1 = fs.OpenTextFile(“C:\Users\notimportant\Desktop\data.txt”, ForReading) 
Dim str,str1
str=fs1.ReadAll
Msgbox str
Do while fs1.AtEndofStream
str1=fs1.ReadLine
Msgbox str1
Loop
fs1.Close

The goal here is to take my ipconfig results, print them to data.txt, wait 3 seconds, and then print the contents of the data file into a msgbox with all the contents of data.txt

I appreciate all the assistance.. I'm fairly new to VBS

Upvotes: 1

Views: 61

Answers (1)

Hackoo
Hackoo

Reputation: 18837

  • First : Pay attention when you copy and paste code from some blogs on internet because, you may encounter quotes like this and this it differ from this quote "

  • Second : You don't need to sleep 3 seconds for waiting.

  • Third : Just open your file for reading and read all contents at once, you don't need to read it line by line. after that you save the variable Contents and show it on MsgBox.

So, I have arranged and simplified your code like this :

Option Explicit
Const ForReading = 1
Dim MyFile,MyCommand,strHomeFolder,fso,oShell,f,Contents,Title
Title = "Execute Command Line and save results in file and show on MsgBox"
Set oShell = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
strHomeFolder = oShell.ExpandEnvironmentStrings("%USERPROFILE%")
MyFile = strHomeFolder & "\Data.txt"
MyCommand = "ipconfig /all >"& MyFile &""
Call Execute(MyCommand)
Set f = fso.OpenTextFile(MyFile,ForReading)
Contents = f.ReadAll
MsgBox Contents,vbInformation,Title
'-----------------------------------------
Function Execute(StrCmd)
   Dim ws,MyCmd,Result
   Set ws = CreateObject("wscript.Shell")
   MyCmd = "CMD /C " & StrCmd & ""
   Result = ws.run(MyCmd,0,True)
   Execute = Result
End Function
'-----------------------------------------

Upvotes: 1

Related Questions