如何从 VB.NET 运行 DOS/CMD/命令提示符命令?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10261521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to run DOS/CMD/Command Prompt commands from VB.NET?
提问by Steve
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 only found old examples and such ones that do not work (at least for me). I want to use this in my class library, to run Git commands (if that helps?).
这个问题是不言自明的。如果代码只有一行(与“ Process.Start("...")
”有关?),那就太好了。我研究了网络,但只找到了旧的例子和那些不起作用的例子(至少对我来说)。我想在我的类库中使用它来运行 Git 命令(如果有帮助?)。
回答by Steve
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.
- A & B→ 执行命令 A,然后执行命令 B。
- 一个 | B→ 执行命令 A,并将其所有输出重定向到命令 B 的输入。
- A && B→ 执行命令 A,执行命令 A 后评估错误级别,如果退出代码(错误级别)为 0,则仅执行命令 B。
- 一个|| B→ 执行命令 A,评估该命令的退出代码,如果它不是 0,则只执行命令 B。
回答by Saeed A Suleiman
You Can try This To Run Command Then cmd
Exits
你可以试试这个运行命令然后cmd
退出
Process.Start("cmd", "/c YourCode")
You Can try This To Run The Command And Let cmd
Wait For More Commands
你可以试试这个来运行命令并cmd
等待更多命令
Process.Start("cmd", "/k YourCode")
回答by Fütemire
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)
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()
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)
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.
扩展方法需要放置在公共模块中,并<Extension>
在子模块上携带属性。您还需要添加Imports System.Runtime.CompilerServices
到代码文件的顶部。
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
回答by Bernardo Ravazzoni
Sub systemcmd(ByVal cmd As String)
Shell("cmd /c """ & cmd & """", AppWinStyle.MinimizedFocus, True)
End Sub
回答by vincent
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
这也有效