VBScript Tutorials - Herong's Tutorial Examples - v6.02, by Herong Yang
"oShell.Exec(cmd)" - Running System Command with a Script
This section provides a tutorial example on how to run a system command with a VBScript code. Command output and status can be monitored with WshScriptExec properties.
As mentioned in the previous section, WSH offers offers runtime objects to perform system administration task.
Here is a tutorial example that uses WshShell object to run a system command and obtaining its output:
' StdIn_StdOut.vbs '- Copyright (c) 1998 HerongYang.com. All Rights Reserved. Dim oShell, oExec, sLine Set oShell = CreateObject("WScript.Shell") Set oExec = oShell.Exec("ping localhost") ' Reading the output of the shell command thread Do While Not oExec.StdOut.AtEndOfStream sLine = oExec.StdOut.ReadLine WScript.StdOut.WriteLine "Output: " & sLine WScript.Sleep 10 Loop ' Waiting for the shell command thread to end ' In case the output ends before the command Do While oExec.Status = 0 WScript.Sleep 100 Loop
When I ran it on my machine, I got:
C:\herong>cscript Shell_Exec.vbs Output: Output: Pinging localhost [127.0.0.1] with 32 bytes of data: Output: Output: Reply from 127.0.0.1: bytes=32 time<1ms TTL=128 Output: Reply from 127.0.0.1: bytes=32 time<1ms TTL=128 Output: Reply from 127.0.0.1: bytes=32 time<1ms TTL=128 Output: Reply from 127.0.0.1: bytes=32 time<1ms TTL=128 Output: Output: Ping statistics for 127.0.0.1: Output: Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Output: Approximate round trip times in milli-seconds: Output: Minimum = 0ms, Maximum = 0ms, Average = 0ms
Table of Contents
Introduction of VBScript - Visual Basic Scripting Edition
Variant Data Type, Subtypes, and Literals
Numeric Comparison Operations and Logical Operations
String Operations - Concatenation and Comparison
Variable Declaration and Assignment Statement
Expression and Order of Operation Precedence
Statement Syntax and Statement Types
Array Data Type and Related Statements
Array References and Array Assignment Statements
Conditional Statements - "If ... Then" and "Select Case"
Loop Statements - "For", "While", and "Do"
"Function" and "Sub" Procedures
Inspecting Variables Received in Procedures
Error Handling Flag and the "Err" Object
Regular Expression Pattern Match and Replacement
scrrun.dll - Scripting Runtime DLL Library
IE Web Browser Supporting VBScript
IIS ASP Server Supporting VBScript
What is WSH (Windows Script Host)?
"cscript.exe/wscript.exe" Command Version and Options
"WScript" Runtime Object Hierarchy
►"oShell.Exec(cmd)" - Running System Command with a Script