Related Items  

Linux and Windows IT Support  

dedicated-technology-experts

Windows, Apple and Linux IT support and services.

For Software and Web Development.

Running external command (VBS & WSH)

PrintE-mail

VBSccript_file_format_iconThere are various ways to execute an external command from VBS. Here are a few examples.

1. Using Exec

If you want to run an application in a child command-shell, providing access to the StdIn/StdOut/StdErr streams:

Example 1: Capturing the exit code:

Dim WshShell, oExec
Set WshShell = CreateObject("WScript.Shell")

Set oExec = WshShell.Exec("notepad")

Do While oExec.Status = 0
WScript.Sleep 100
Loop

WScript.Echo oExec.Status

Example 2: Capturing the output:

Wscript.Echo runCMD("dir C:\")
Function runCMD(strRunCmd)
Set objShell = WScript.CreateObject("WScript.Shell")
Set objExec = objShell.Exec(strRunCmd)

strOut = ""

Do While Not objExec.StdOut.AtEndOfStream
strOut = strOut & objExec.StdOut.ReadLine()
Loop

Set objShell = Nothing
Set objExec = Nothing

runCMD = strOut
End Function

2.Using Run

If you want to run a program in a new process:

object .Run(strCommand, [intWindowStyle], [bWaitOnReturn])

intWindowStyle is an integer value indicating window style. Here's a table of styles:

intWindowStyle Description
0 Hides the window and activates another window.
1 Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when displaying the window for the first time.
2 Activates the window and displays it as a minimized window.
3 Activates the window and displays it as a maximized window.
4 Displays a window in its most recent size and position. The active window remains active.
5 Activates the window and displays it in its current size and position.
6 Minimizes the specified window and activates the next top-level window in the Z order.
7 Displays the window as a minimized window. The active window remains active.
8 Displays the window in its current state. The active window remains active.
9 Activates and displays the window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when restoring a minimized window.
10 Sets the show-state based on the state of the program that started the application.

bWaitOnReturn an option to either wait for the process to return or continue without it (can be either true or false)

Example 1: change directory to C:\ and run dir command:

Dim oShell
Set oShell = WScript.CreateObject ("WScript.Shell")
oShell.run "cmd /K CD C:\ & Dir"
Set oShell = Nothing

Add your comment

Your name:
Subject:
Comment:
  The word for verification. Lowercase letters only with no spaces.
Word verification:
yvComment v.1.24.0
   
Copyright © 1999 - 2024 Virtual Helpme | Business IT Support | Original Template: Allrounder