Running command-line tools

These examples show how to run command-line tools from within a VBScript, capturing the tool’s output.

' Essentials - by Don Jones
' Run cmdline tools
' This shows how to launch a command-line
' tool and retrieve its output into a string variable
' to then do something with it. For example, you might
' use the InStr() function to determine if a specific
' string exists in the command's output.

‘ The trick is to use the WshShell object’s Exec, not Run, method
Dim objShell, objExec
Set objShell = CreateObject(“WScript.Shell”)

‘run the command-line command – just as you’d type it into
‘Start > Run. Avoid running Cmd.Exe directly, because it
‘doesn’t actually return any output itself.
Set objExec = objShell.Exec(“dir”)

‘objExec now represents the executing command. Our script
‘doesn’t exactly wait for that to finish, but we can
‘keep in touch with it. objExec is an instance of the
‘WshScriptExec object, if you want to read the docs on it

‘we can wait for it to finish running
Do Until objExec.Status = 1
WScript.Sleep 100

‘we can get the exit code (note that this method
‘isn’t in the WSH Type Library so it doesn’t show up
‘in a lot of object browsers or code hinting menus,
‘but it should work on the latest version of WSH)
WScript.Echo “Exited with ” & objExec.ExitCode

‘here’s where we get the output into a string var
Dim strOutput
If Not objExec.StdOut.AtEndOfStream Then
strOutput = strOutput & objExec.StdOut.Read(1)
End If
WScript.Echo strOutput