Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vbs how to get result from a command line command

I want to get the result of a simple command from the command line (cmd.exe) using a Windows script (.vbs). How is this done? I haven't been able to find a good/simple example or explanation. You could use the "date" or "time" command to provide an example with. Such as:

enter image description here

P.S. I am able to write the script code that opens cmd.exe and sends the command.

Thanks!

like image 230
user1387865 Avatar asked Oct 01 '12 20:10

user1387865


1 Answers

When in doubt, read the documentation. You probably want something like this:

Set p = CreateObject("WScript.Shell").Exec("%COMSPEC% /c date /t")
Do While p.Status = 0
  WScript.Sleep 100
Loop
WScript.Echo p.StdOut.ReadAll

Edit: When using Exec() you pass input via the .StdIn descriptor, not via SendKeys() (which is a rather unreliable way of passing input anyway).

%COMSPEC% is a system environment variable with the full path to cmd.exe and the /c option makes cmd.exe exit after the command (date /t in the example) is finished.

If the command indicates success/failure with an exit code, you can check the ExitCode property after the command finished.

If p.Status <> 0 Then WScript.Echo p.ExitCode

Edit2: Instead of using atprogram interactively, can you construct commandlines that will perform particular tasks without user interaction? With non-interactive commandlines something like this might work:

prompt = "C:\>"
atprogram_cmdline_1 = "atprogram.exe ..."
atprogram_cmdline_2 = "atprogram.exe ..."
'...

Function ReadOutput(p)
  text = ""
  Do Until Right(text, Len(prompt)) = prompt
    text = text & p.StdOut.Read(1)
  Loop
  ReadOutput = text
End Function

Set cmd = CreateObject("WScript.Shell").Exec("%COMSPEC% /k")
ReadOutput cmd  ' skip over first prompt

cmd.StdIn.WriteLine(atprogram_cmdline_1)
WScript.Echo ReadOutput(cmd)
cmd.StdIn.WriteLine(atprogram_cmdline_2)
WScript.Echo ReadOutput(cmd)
'...

cmd.Terminate  ' exit CMD.EXE

%COMSPEC% /k spawns a command prompt without running a command. The /k prevents it from closing. Because it isn't closing automatically, you can't use the While p.Status = 0 loop here. If a command needs some time to finish, you need to WScript.Sleep a number of seconds.

Via cmd.StdIn.WriteLine you can run commandlines in the CMD instance. The function ReadOutput() reads the output from StdOut until the next prompt appears. You need to look for the prompt, because read operations are blocking, so you can't simply say "read all that's been printed yet".

After you're finished you quit CMD.EXE via cmd.Terminate.

like image 187
Ansgar Wiechers Avatar answered Sep 30 '22 07:09

Ansgar Wiechers