Script Tips

Run with It

Essential redux: Use VBScript to run a command-line tool and capture its output.

Last month’s focus on scripting essentials was pretty popular. (Please keep your comments coming and post any questions in the Forums on http://ScriptingAnswers.com). I'll continue this time with another essential: how to run a command-line tool from within VBScript, and capture its output into a string variable.

The script is pretty straightforward, and uses the WshShell object to do its work:

'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
Loop

'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

Once you’ve got that strOutput variable, use InStr() to see if it contains some word or phrase that you’re interested in. Before the Win32_PingStatus WMI class came out in Windows XP/2003, you could use this trick to run the Ping.exe command, and then check to see if the results contained “Reply from,” which told you that the computer you pinged was reachable.

About the Author

Don Jones is a multiple-year recipient of Microsoft’s MVP Award, and is Curriculum Director for IT Pro Content for video training company Pluralsight. Don is also a co-founder and President of PowerShell.org, a community dedicated to Microsoft’s Windows PowerShell technology. Don has more than two decades of experience in the IT industry, and specializes in the Microsoft business technology platform. He’s the author of more than 50 technology books, an accomplished IT journalist, and a sought-after speaker and instructor at conferences worldwide. Reach Don on Twitter at @concentratedDon, or on Facebook at Facebook.com/ConcentratedDon.

comments powered by Disqus
Most   Popular