# Visual Basic > Visual Basic FAQs >  Classic VB/API - How Do I Run DOS Commands From VB?

## RobDog888

You can run DOS commands from VB via the command window (CMD.exe). There are a few easy ways to do this as shown below. The CMD.exe file is not supported on 95/98 but those OS' do have Command.com

As long as you're only needing to generate an output this is sufficient, but if you need to read the data back in then you may want to use other methods to detect the completion of the process or a more advanced method to redirect the output from the console window (as can be seen in this FAQ thread).


You can Shell a DOS Batch file (.bat)

VB Code:
Option Explicit
 Private Sub Command1_Click()
    Shell "C:\MyFile.bat", vbNormalFocus
End Sub
You can use a more powerful version of the Shell function called the ShellExecute API.

VB Code:
Option Explicit
 Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, _
ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
 Private Declare Function GetSystemDirectory Lib "kernel32.dll" Alias "GetSystemDirectoryA" (ByVal lpBuffer As String, _
ByVal nSize As Long) As Long
 Private Const SW_HIDE As Long = 0
Private Const SW_SHOWNORMAL As Long = 1
  Private Sub Command2_Click()
    ShellExecute Me.hwnd, "Open", "C:\MyFile.bat", vbNullString, "C:\", SW_SHOWNORMAL
End Sub
 'Or directly pass the parameters to the DOS console...
Private Sub Command3_Click()
 'Output: >
'Append: >>
'Close DOS Console: /C
'Keep DOS Console open: /K
    ShellExecute Me.hwnd, "Open", "C:\Windows\System32\CMD.exe", " /C Dir C:\ > C:\Dir.txt", "C:\", SW_SHOWNORMAL
End Sub
 'And finally you can add dynamic location of the CMD.exe file.
Private Sub Command4_Click()
    Dim strBuff As String * 255
    Dim strPath As String
    Dim x As Integer
    x = GetSystemDirectory(strBuff, Len(strBuff))
    If x > 0 Then
        x = InStr(strBuff, vbNullChar)
        If x > 0 Then
            strPath = Left$(strBuff, x - 1)
        End If
        ShellExecute Me.hwnd, "Open", strPath & "\CMD.exe", " /C Dir C:\  > C:\Dir.txt", "C:\", SW_SHOWNORMAL
    End If
End Sub

----------

