How can I execute cmd commands by vb.net? - vb.net

I recently building codes for cmd commands by vb.net. It cannot work by just popping up the same form. I hope that someone can fix it.
Imports System.IO
Public Class Form1
Private Sub Execute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Execute.Click
Result.Text = RunCmd(Command.Text)
End Sub
Private Function RunCmd(ByVal cmd As String) As String
Dim p As Process = New Process
With p.StartInfo
.FileName = "cmd.exe"
.Arguments = "/c " + cmd
.UseShellExecute = False
.RedirectStandardInput = True
.RedirectStandardOutput = True
.RedirectStandardError = True
.CreateNoWindow = True
End With
p.Start()
'p.StandardInput.WriteLine(command);
'p.StandardInput.WriteLine("exit");
Dim reader As StreamReader = p.StandardOutput
Dim output As String = reader.ReadToEnd()
Return output
End Function
End Class
I expect that I can run the command in the textbox. But it can't.

Related

how to execute a command when a vb form button is "clicked" from a textbox string and then display the output in a richtextbox

I'm new to coding. I'm cant seem to figure out/find a solution on how to make my code work correctly when I try to execute.
I have built a VB form that creates a command string in a TextBox depending on selections made from a variety of form selections. I'm appending text to the textbox per the selections to create said command string. Once the command is finished being built I want to be able to execute the built textbox.text using a button to execute it, and have the output be displayed in a RichTextBox in my form.
added info.
Below is the section of code I'm trying to get working. I wasn't sure if I should add the code to the post or not after reading the creating a post section.
lets say the text in the textbox1 would be something like.
psexec.exe \PCname c:\program files\mcafee\virusscan enterprise\mcupdate.exe \update \quiet
Private Sub Button12_Click(sender As Object, e As EventArgs) Handles Button12.Click
System.Windows.Forms.Application.DoEvents()
Dim myprocess As New Process
Dim startinfo As New ProcessStartInfo("cmd.exe")
startinfo.Arguments = TextBox1.Text
startinfo.UseShellExecute = False
startinfo.RedirectStandardOutput = True
startinfo.CreateNoWindow = True
myprocess.StartInfo = startinfo
myprocess.StartInfo.Arguments = TextBox1.Text
myprocess.Start()
Dim str1 As String = ""
Using MyStreamReader As IO.StreamReader = myprocess.StandardOutput
str1 = str1 & MyStreamReader.ReadToEnd
End Using
RichTextBox1.Text = str1
end sub
Note: Working version is below.
Private Sub Button12_Click(sender As Object, e As EventArgs) Handles Button12.Click
System.Windows.Forms.Application.DoEvents()
Dim myprocess As New Process
Dim startinfo As New ProcessStartInfo(TextBox3.Text, TextBox1.Text)
startinfo.UseShellExecute = False
startinfo.RedirectStandardOutput = True
startinfo.CreateNoWindow = True
myprocess.StartInfo = startinfo
myprocess.Start()
Dim str1 As String = ""
Using MyStreamReader As IO.StreamReader = myprocess.StandardOutput
str1 = str1 & MyStreamReader.ReadToEnd
End Using
RichTextBox1.Text = str1
End Sub

I am trying to read the Output from the Openfiles.exe and this is not working

This is to run the openfiles.exe and return the output from it
If i run openfiles.exe at the command line it works as expected
When I run it here there is no error but i get nothing in the Messagebox
Dim NewProcess As New Process()
With NewProcess.StartInfo
.FileName = "openfiles.exe"
.Arguments = "/query /s FakeServer/fo csv /V /U FakeDomain\Fakeuser/P pword"
.RedirectStandardOutput = True
.RedirectStandardError = True
.RedirectStandardInput = True
.UseShellExecute = False
.WindowStyle = ProcessWindowStyle.Normal
.CreateNoWindow = False
End With
NewProcess.Start()
System.Threading.Thread.Sleep(5000)
MsgBox(NewProcess.StandardOutput.ReadToEnd)
This is just a sample code that I have that is similar to what you are trying to do. However, my app was trying to run a command using cmd.exe and display the result in real time to a textbox. You can try to modify it accordingly.
Dim cmd As New Process()
Dim strCommandLine As String = "Echo Hello World"
cmd.StartInfo.FileName = "cmd.exe"
cmd.StartInfo.RedirectStandardError = True
cmd.StartInfo.RedirectStandardInput = True
cmd.StartInfo.RedirectStandardOutput = True
cmd.StartInfo.CreateNoWindow = True
cmd.StartInfo.UseShellExecute = False
cmd.EnableRaisingEvents = True
Application.DoEvents()
AddHandler cmd.ErrorDataReceived, AddressOf OutputHandler
AddHandler cmd.OutputDataReceived, AddressOf OutputHandler
cmd.Start()
cmd.StandardInput.WriteLine(strCommandLine)
cmd.StandardInput.Flush()
cmd.StandardInput.Close()
cmd.BeginErrorReadLine()
cmd.BeginOutputReadLine()
cmd.Close()
Delegate Sub UpdateTextBoxDelg(text As String)
Public myDelegate As UpdateTextBoxDelg = New UpdateTextBoxDelg(AddressOf UpdateTextBox)
Public Sub UpdateTextBox(text As String)
txtOutput.Text += text & Environment.NewLine
txtOutput.SelectionStart = txtOutput.Text.Length
txtOutput.ScrollToCaret()
End Sub
Private Sub OutputHandler(sender As Object, e As DataReceivedEventArgs)
If Me.InvokeRequired = True Then
Me.Invoke(myDelegate, e.Data)
Else
UpdateTextBox(e.Data)
End If
End Sub

Read Standard Output and check status of multiple processes VB.NET

I run multiple command line processes, starting them in a loop. It works and starts all of them async.
Public Sub DoWork
Dim i As Integer = 0
While (Args_reader.Peek() > -1)
i = i + 1
MyArg = Args_reader.ReadLine
Dim MyArg As String
Dim MyProcess(i) As Process
MyProcess(i) = New Process
With MyProcess(i).StartInfo
.FileName = MyFile
.Arguments = MyArg
.UseShellExecute = False
.CreateNoWindow = True
.RedirectStandardInput = True
.RedirectStandardOutput = True
.RedirectStandardError = True
.WindowStyle = ProcessWindowStyle.Hidden
End With
MyProcess(i).Start()
End While
Args_reader.Close()
i = 0
End Sub
Haw can I read stdOutput for all of them and check their status?
I need to wait until they finish to continue executing the program.
I would recommend you to assign async events to every process inside a loop, so they get fired when that process has any output. Standard Output or Error Output:
Dim Proceso As New Process
'Add the event handlers:
AddHandler Proceso.OutputDataReceived, AddressOf CallbackProcesoAsync
AddHandler Proceso.ErrorDataReceived, AddressOf ErrorDataReceivedAsync
Dim startInfo As New ProcessStartInfo
startInfo.FileName = execFile
startInfo.RedirectStandardOutput = True
startInfo.RedirectStandardError = True
startInfo.CreateNoWindow = False
Proceso.StartInfo = startInfo
Proceso.Start()
the async events should be something like this:
Private Sub CallbackProcesoAsync(sender As Object, args As System.Diagnostics.DataReceivedEventArgs)
If Not args.Data Is Nothing AndAlso Not String.IsNullOrEmpty(args.Data) Then
'args.Data have the output
End If
End Sub
Private Sub ErrorDataReceivedAsync(sender As Object, args As System.Diagnostics.DataReceivedEventArgs)
If Not args.Data Is Nothing AndAlso Not String.IsNullOrEmpty(args.Data) Then
'args.Data have the output
End If
End Sub

VB.NET Process Redirect Output Not Working

I'm trying to redirect the output from a command-line application in VB.NET, and for some reason it fails to redirect the output. Here's my code:
Dim myProcess As Process = New Process
myProcess.StartInfo.FileName = "g++"
myProcess.StartInfo.Arguments = CMDLineCommand
myProcess.StartInfo.UseShellExecute = False
myProcess.StartInfo.RedirectStandardOutput = True
myProcess.StartInfo.RedirectStandardError = True
myProcess.StartInfo.CreateNoWindow = True
myProcess.Start()
Dim output As String = myProcess.StandardOutput.ReadToEnd
myProcess.WaitForExit()
CMDLineOutputTextBox.Text = output
Does anybody know why it's not being redirected? Thanks in advance!
-Neil
EDIT: Here's my full code, in case there's anything weird with my syntax:
Dim myProcess As Process = New Process
myProcess.StartInfo.FileName = "g++"
myProcess.StartInfo.Arguments = CMDLineCommand
myProcess.StartInfo.UseShellExecute = False
myProcess.StartInfo.RedirectStandardOutput = True
myProcess.StartInfo.RedirectStandardError = True
myProcess.StartInfo.CreateNoWindow = True
myProcess.EnableRaisingEvents = True
AddHandler myProcess.OutputDataReceived, AddressOf GotData
myProcess.Start()
CMDLineOutputTextBox.Text = ""
myProcess.BeginOutputReadLine()
Later on...
Private Sub GotData(sendingProcess As Object, outLine As DataReceivedEventArgs)
If Not String.IsNullOrEmpty(outLine.Data) Then
SetText(outLine.Data)
End If
End Sub
Delegate Sub SetTextCallback(value As String)
Private Sub SetText(ByVal value As String)
If Me.CMDLineOutputTextBox.InvokeRequired Then
Dim d As New SetTextCallback(AddressOf SetText)
Me.Invoke(d, New Object() {value})
Else
Me.CMDLineOutputTextBox.Text += value + Environment.NewLine
End If
End Sub
Anything weird?
Your method will work, provided by the time you hit the line where you read the output to the end, all of the output is there. Since you are using g++, I assume that may not always be the case. You will probably be better off using the OutputDataReceived Event and capturing the data from that.
Dim myProcess As Process = New Process
myProcess.StartInfo.FileName = "ping"
myProcess.StartInfo.Arguments = "www.google.com"
myProcess.StartInfo.UseShellExecute = False
myProcess.StartInfo.RedirectStandardOutput = True
myProcess.StartInfo.RedirectStandardError = True
myProcess.StartInfo.CreateNoWindow = True
myProcess.EnableRaisingEvents = True
AddHandler myProcess.OutputDataReceived, AddressOf GotData
myProcess.Start()
myProcess.BeginOutputReadLine()
Then you handle the event like this:
Private Sub GotData(sendingProcess As Object, outLine As DataReceivedEventArgs)
If Not String.IsNullOrEmpty(outLine.Data) Then
SetText(outLine.Data)
End If
End Sub
Delegate Sub SetTextCallback(value As String)
Private Sub SetText(ByVal value As String)
If Me.TextBox3.InvokeRequired Then
Dim d As New SetTextCallback(AddressOf SetText)
Me.Invoke(d, New Object() {value})
Else
Me.TextBox3.Text += value + Environment.NewLine
End If
End Sub
I have noticed the waitforExit seems to make the code lock during the invoke.required check. When I take out the waitforexit it works.

Console output to String

I'm working on a little app that requires the results of a dsquery and dsget set in a string for clean up (replacing spaces and other not needed characters). I can display the results of the stream with ReadToEnd - but can't seem to find anything on getting it into a string.
VB.net - visual basic 2010
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim p As New Process
p.StartInfo.UseShellExecute = False
p.StartInfo.CreateNoWindow = True
p.StartInfo.FileName = "program"
p.StartInfo.Arguments = "lots here"
p.StartInfo.RedirectStandardOutput = True
p.Start()
Dim reader As StreamReader = p.StandardOutput
p.WaitForExit()
MsgBox(reader.ReadToEnd)
End Sub
just write
dim ProcOutput as string
ProcOutput = reader.ReadToEnd()
instead of the last line.
if that doesn't help, then I suggest you check out this article:
http://www.codeproject.com/KB/threads/launchprocess.aspx