Question

If I am using VBS to run some CMD commands, in this example ping, how could I write the command to a text file using VBS not DOS?

Set objCmdTest = WScript.CreateObject ("WScript.Shell")
Set Output = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\vbs\test.txt",8,true)

Output.WriteLine (objCmdTest.run ("ping failboat"))
Output.WriteLine (objCmdTest.run ("ping 8.8.8.8"))

So this is what I'm working with however what happens is; The script runs, the file is made, 2 command prompts open to run the pings and finally the text inside the file reads:

0
0

When I'd much prefer it to have the ping output.

FYI: Please don't offer suggestions that require me to use DOS for the writing, I'd like to see how VBS can do what I need for multiple reasons, thanks!

Was it helpful?

Solution

The instruction Output.WriteLine (objCmdTest.run ("ping failboat")) will write the return value of the Run method to the output file. If you want to append the command output to an output file you have to either redirect the output in the command:

objCmdTest.run "%COMSPEC% /c ping failboat >>C:\vbs\test.txt", 0, True

or use Exec instead of Run:

Set ping = objCmdTest.Exec("ping failboat")
Do While ping.Status = 0
  WScript.Sleep 100
Loop
Output.WriteLine ping.StdOut.ReadAll

OTHER TIPS

WScript.Shell's run method returns the process's exit code. In order to get access to an application's output, you need to use the exec method instead, and use the object that returns to get access to the process's standard output through its StdOut property.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top