Share via


DOS Scripts From Visual Basic.Net

How To execute a dos script in Visual Basic without creating an external process. Not all DOS commands can be executed with this, such as CLS, diskpart, echo, etc.... If you discover unsupported commands, please add them to this list: Unsupported Dos Commands:

  • CLS
  • Echo
  • DiskPart
  • ?
Option Strict On
Public Class  Form1
    Private Sub  Button1_Click(ByVal  sender As  System.Object, ByVal  e As  System.EventArgs) Handles Button1.Click
        Dim OFD As New  OpenFileDialog With  {.Filter = "DOS Batch Files|*.bat", .Multiselect = False}
        If OFD.ShowDialog = DialogResult.OK Then
            ExecuteBatchFile(OFD.FileName)
        End If
    End Sub
    Public Function  ExecuteDosScript(ByVal BatchScriptLines As List(Of String)) As  String
        Dim OutputString As String  = String.Empty
        Using Process As  New Process
            AddHandler Process.OutputDataReceived, Sub(sendingProcess As  Object, outLine As DataReceivedEventArgs)
                                                       OutputString = OutputString & outLine.Data & vbCrLf
                                                   End Sub
            Process.StartInfo.FileName = "cmd"
            Process.StartInfo.UseShellExecute = False
            Process.StartInfo.CreateNoWindow = True
            Process.StartInfo.RedirectStandardInput = True
            Process.StartInfo.RedirectStandardOutput = True
            Process.StartInfo.RedirectStandardError = True
            Process.Start()
            Process.BeginOutputReadLine()
            Using InputStream As  System.IO.StreamWriter = Process.StandardInput
                InputStream.AutoFlush = True
                For Each  ScriptLine As  String In  BatchScriptLines
                    InputStream.Write(ScriptLine & vbCrLf)
                Next
            End Using
            Do
                Application.DoEvents()
            Loop Until  Process.HasExited
        End Using
        Return OutputString
    End Function
    Sub ExecuteBatchFile(ByVal Filename As String)
        If Not  IO.Path.GetExtension(Filename).ToLower = ".bat" Then  Throw New  Exception("Invalid batch file extension")
        Dim BatchScriptLines As List(Of String) = IO.File.ReadAllLines(Filename).ToList
        MsgBox(ExecuteDosScript(BatchScriptLines))
    End Sub
End Class

Please check out my other Technet Wiki articles!