Home

Running DOS Commands in VB

This sample project demonstrates how to read environment variables and execute a DOS command in a Visual Basic application.

Making the DOS Commands Project

  1. Open a new project in Visual Basic 6.0.
  2. Select Project1 Properties on the Project menu, set the Startup Object to Sub Main, and click OK. .
  3. Copy the following code into the form. Option Explicit

    Sub Main()
        'Passes the DOS command as a parameter to the RunCommand procedure.
        RunCommand "dir /b > c:\temp.txt"
    End Sub

    Public Sub RunCommand(strCommand As String)
        'Runs the DOS command.
        Shell Environ("COMSPEC") & " /c " & strCommand, vbHide
    End Sub
  4. Run the project. Look for the temp.txt file in the root folder of your C: drive and examine its contents.

Comments

This project is loaded with delightful little twists from out of Windows' ancient history. Prepare yourself to delve into the arcana of DOS commands and switches, command interpreters, and environment variables. The RunCommand procedure is the action is in this sample...all one line of it. RunCommand hands the vbHide constant, a DOS command passed in as a parameter, and an environment variable to the Shell function to execute. I'll break all this down, starting at the end and working to the front.

First, the vbHide constant is just a constant that tells the Shell function to not display a window. In front of this, the variable strCommand contains the string passed in from the Sub Main procedure. In front of that, the /c parameter tells Command.com to run the string that follows as a command, in this case the contents of the variable strCommand. Next, the Environ function returns the location of the command processor, command.com. Finally, the Shell function packages all this together and runs it. By design, the Shell function runs .Exe files. In this case we're passing the following command line to the Shell function to execute: "C:\WINDOWS\COMMAND.COM /c dir /b > c:\temp.txt". Finally, this command line contains two additional switches: the /b parameter tells the Dir command to return filenames only, one per line; and the 'greater than'(>) symbol is a pipe that routes the output of the Dir command to the file Temp.Txt.

That's it! What a lot of twists and turns for just two lines of executable code.

Last changed 9/4/00