How to run DOS/CMD/Command Prompt commands from VB.NET?

前端 未结 5 855
旧时难觅i
旧时难觅i 2020-12-08 16:38

The question is self-explanatory. It would be great if the code was one line long (something to do with \"Process.Start(\"...\")\"?). I researched the web but o

相关标签:
5条回答
  • 2020-12-08 16:46

    You could try this method:

    Public Class MyUtilities
        Shared Sub RunCommandCom(command as String, arguments as String, permanent as Boolean) 
            Dim p as Process = new Process() 
            Dim pi as ProcessStartInfo = new ProcessStartInfo() 
            pi.Arguments = " " + if(permanent = true, "/K" , "/C") + " " + command + " " + arguments 
            pi.FileName = "cmd.exe" 
            p.StartInfo = pi 
            p.Start() 
        End Sub
    End Class
    

    call, for example, in this way:

    MyUtilities.RunCommandCom("DIR", "/W", true)
    

    EDIT: For the multiple command on one line the key are the & | && and || command connectors

    • A & B → execute command A, then execute command B.
    • A | B → execute command A, and redirect all it's output into the input of command B.
    • A && B → execute command A, evaluate the errorlevel after running Command A, and if the exit code (errorlevel) is 0, only then execute command B.
    • A || B → execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute command B.
    0 讨论(0)
  • 2020-12-08 16:46

    You Can try This To Run Command Then cmd Exits

    Process.Start("cmd", "/c YourCode")
    

    You Can try This To Run The Command And Let cmd Wait For More Commands

    Process.Start("cmd", "/k YourCode")
    
    0 讨论(0)
  • 2020-12-08 16:59
    Imports System.IO
    Public Class Form1
        Public line, counter As String
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            counter += 1
            If TextBox1.Text = "" Then
                MsgBox("Enter a DNS address to ping")
            Else
                'line = ":start" + vbNewLine
                'line += "ping " + TextBox1.Text
                'MsgBox(line)
                Dim StreamToWrite As StreamWriter
                StreamToWrite = New StreamWriter("C:\Desktop\Ping" + counter + ".bat")
                StreamToWrite.Write(":start" + vbNewLine + _
                                    "Ping -t " + TextBox1.Text)
                StreamToWrite.Close()
                Dim p As New System.Diagnostics.Process()
                p.StartInfo.FileName = "C:\Desktop\Ping" + counter + ".bat"
                p.Start()
            End If
        End Sub
    End Class
    

    This works as well

    0 讨论(0)
  • 2020-12-08 17:00
    Sub systemcmd(ByVal cmd As String)
        Shell("cmd /c """ & cmd & """", AppWinStyle.MinimizedFocus, True)
    End Sub
    
    0 讨论(0)
  • 2020-12-08 17:04

    I was inspired by Steve's answer but thought I'd add a bit of flare to it. I like to do the work up front of writing extension methods so later I have less work to do calling the method.

    For example with the modified version of Steve's answer below, instead of making this call...

    MyUtilities.RunCommandCom("DIR", "/W", true)

    I can actually just type out the command and call it from my strings like this...

    Directly in code.

    Call "CD %APPDATA% & TREE".RunCMD()

    OR

    From a variable.

    Dim MyCommand = "CD %APPDATA% & TREE"
    MyCommand.RunCMD()
    

    OR

    From a textbox.

    textbox.text.RunCMD(WaitForProcessComplete:=True)


    Extension methods will need to be placed in a Public Module and carry the <Extension> attribute over the sub. You will also want to add Imports System.Runtime.CompilerServices to the top of your code file.

    There's plenty of info on SO about Extension Methods if you need further help.


    Extension Method

    Public Module Extensions
    ''' <summary>
    ''' Extension method to run string as CMD command.
    ''' </summary>
    ''' <param name="command">[String] Command to run.</param>
    ''' <param name="ShowWindow">[Boolean](Default:False) Option to show CMD window.</param>
    ''' <param name="WaitForProcessComplete">[Boolean](Default:False) Option to wait for CMD process to complete before exiting sub.</param>
    ''' <param name="permanent">[Boolean](Default:False) Option to keep window visible after command has finished. Ignored if ShowWindow is False.</param>
    <Extension>
    Public Sub RunCMD(command As String, Optional ShowWindow As Boolean = False, Optional WaitForProcessComplete As Boolean = False, Optional permanent As Boolean = False)
        Dim p As Process = New Process()
        Dim pi As ProcessStartInfo = New ProcessStartInfo()
        pi.Arguments = " " + If(ShowWindow AndAlso permanent, "/K", "/C") + " " + command
        pi.FileName = "cmd.exe"
        pi.CreateNoWindow = Not ShowWindow
        If ShowWindow Then
            pi.WindowStyle = ProcessWindowStyle.Normal
        Else
            pi.WindowStyle = ProcessWindowStyle.Hidden
        End If
        p.StartInfo = pi
        p.Start()
        If WaitForProcessComplete Then Do Until p.HasExited : Loop
    End Sub
    End Module
    
    0 讨论(0)
提交回复
热议问题