How to Copy CMD Results into Textbox on VB.Net Project - vb.net

I'm working on a Project by VB.net and i'm using CMD to excute commands i want to Know how to copy the Results of the CMD into a textbox on my Main Form

Take a look at the accepted answer here: Get the output of a shell Command in VB.net. That is probably what you need.
Also, here is a version of the code that puts the result into the textbox:
Dim oProcess As New Process()
Dim oStartInfo As New ProcessStartInfo("ApplicationName.exe", "arguments")
oStartInfo.UseShellExecute = False
oStartInfo.RedirectStandardOutput = True
oProcess.StartInfo = oStartInfo
oProcess.Start()
Dim sOutput As String
Using oStreamReader As System.IO.StreamReader = oProcess.StandardOutput
sOutput = oStreamReader.ReadToEnd()
End Using
txtOutput.Text = sOutput 'txtOutput being the output textbox.

I hope this helps.
Dim proc As New Process
proc.StartInfo.FileName = "C:\ipconfig.bat"
proc.StartInfo.UseShellExecute = False
proc.StartInfo.RedirectStandardOutput = True
proc.Start()
proc.WaitForExit()
Dim output() As String = proc.StandardOutput.ReadToEnd.Split(CChar(vbLf))
For Each ln As String In output
RichTextBox1.AppendText(ln & vbNewLine)
lstScan.Items.Add(ln & vbNewLine)
Next
'Created a file in batch with 2 lines as shown below:
echo off
ipconfig
' save this file as ipconfig.bat or whatever name u want.
' if you didn't want that you could use any command on there like this:
echo off
dir/s
or
echo off
cd\
dir/s
pause

Related

The process tried to write to a nonexistent pipe vb.net

I'm currently writing a sub in vb.net that is supposed to create and/or erase tasks in the task scheduler that comes with windows 10. The creation part works fine, but when I try to erase the task I get this error in the visual studio console: "The process tried to write to a nonexistent pipe", and the task is (of course) still there. I've looked for a solution but can't find anything similar. Here is the code:
Private Sub SimpleButton2_Click(sender As Object, e As EventArgs) Handles sbAutoRun.Click
Dim CMDThread As New Threading.Thread(AddressOf CMDAutomate)
CMDThread.Start()
End Sub
Private Sub CMDAutomate()
Dim myprocess As New Process
Dim StartInfo As New System.Diagnostics.ProcessStartInfo
Dim sTime As String = teAutoRun.Time.ToString("HH:mm")
Dim sCmdCommand As String = "SCHTASKS /CREATE /SC DAILY /TN ""MyTasks\task"" /TR ""'" & My.Application.Info.DirectoryPath & "\program.exe' Auto"" /ST " & sTime & " /RL HIGHEST"
Dim sCmdCommand2 As String = "SCHTASKS /DELETE /TN ""MyTasks\task"""
My.Settings.AutoRun = ceAutoRun.Checked
StartInfo.FileName = "cmd" 'starts cmd window
StartInfo.RedirectStandardInput = True
StartInfo.RedirectStandardOutput = True
StartInfo.CreateNoWindow = True '<---- if you want to not create a window
StartInfo.UseShellExecute = False 'required to redirect
myprocess.StartInfo = StartInfo
myprocess.Start()
Dim SR As System.IO.StreamReader = myprocess.StandardOutput
Dim SW As System.IO.StreamWriter = myprocess.StandardInput
If My.Settings.AutoRun And Not My.Settings.AutoRunExists Then
SW.WriteLine(sCmdCommand)
My.Settings.AutoRunExists = True
Console.WriteLine(sCmdCommand)
ElseIf My.Settings.AutoRun And My.Settings.AutoRunExists Then
SW.WriteLine(sCmdCommand2)
SW.WriteLine("y")
SW.WriteLine(sCmdCommand)
Else
SW.WriteLine(sCmdCommand2)
SW.WriteLine("y")
My.Settings.AutoRunExists = False
Console.WriteLine(sCmdCommand2)
End If
SW.WriteLine("exit") 'exits command prompt window
SW.Close()
SR.Close()
My.Settings.Save()
End Sub
Thanks..
Ps: The commands work fine when entered by hand in the cmd.
Update: Changed this
sCmdCommand2 As String = "SCHTASKS /DELETE /TN ""MyTasks\task"""
SW.WriteLine(sCmdCommand2)
SW.WriteLine("y")
and wrote it like this
sCmdCommand2 As String = "SCHTASKS /DELETE /TN ""MyTasks\task"" /F"
SW.WriteLine(sCmdCommand2)
Now it works fine.

Visual Basic, Capture output from cmd

Sorry if it's asked before, I found out other Solutions too complicated for me..
Anyway, i am trying to search an image via cmd in visual basic code, and save the image path to string, but i cant seem to capture the output from cmd right.
Any help will be appreciated, thanks!.
Code:
Dim imageLocation As String
Dim cmd As New Process
Dim SR As System.IO.StreamReader
cmd.StartInfo.FileName = "cmd.exe"
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
cmd.StartInfo.Arguments = "/C dir /b/s Roey.png"
cmd.Start()
SR = cmd.StandardOutput
imageLocation = SR.ReadLine
UPDATED So i found out saving the output to txt file and then read it can be more simple, so i wrote the following code:
Dim cmd As New Process
cmd.StartInfo.FileName = "cmd.exe"
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
cmd.StartInfo.Arguments = "/C dir /b/s Roey.png >
C:\Users\ירין\Desktop\Roeyyy\path.txt"
cmd.Start()
cmd.WaitForExit()
when i run the
"dir /b/s Roey.png >
C:\Users\ירין\Desktop\Roeyyy\path.txt"
on CMD it wors perfectly, so why isnt it working here? :(
I found this:
Dim MyFilePath As String = Directory.GetFiles([SomePath], "*.png", SearchOption.AllDirectories).
Where(Function(f) f.Contains("Roey.png")).FirstOrDefault()
Solved!
You are a programmer so you search for files.
Imports System.Runtime.InteropServices
Sub Main
'On Error Resume Next
Set fso = CreateObject("Scripting.FileSystemObject")
Dirname = InputBox("Enter Dir name")
ProcessFolder DirName
End Sub
Sub ProcessFolder(FolderPath)
On Error Resume Next
Set fldr = fso.GetFolder(FolderPath)
Set Fls = fldr.files
For Each thing in Fls
msgbox Thing.Name & " " & Thing.path
'fso.copyfile thing.path, "C:\backup"
Next
Set fldrs = fldr.subfolders
For Each thing in fldrs
ProcessFolder thing.path
Next
End Sub

use the cmd command result in case statment

im trying to get the windows license status from cmd by running this code
Dim oProcess As New Process()
Dim oStartInfo As New ProcessStartInfo("cmd.exe", " /c cscript ""%windir%\system32\slmgr.vbs"" /xpr | findstr ""The machine""")
oStartInfo.CreateNoWindow = True
oStartInfo.WindowStyle = ProcessWindowStyle.Hidden
oStartInfo.UseShellExecute = False
oStartInfo.RedirectStandardOutput = True
oProcess.StartInfo = oStartInfo
oProcess.Start()
Dim sOutput As String
Using oStreamReader As System.IO.StreamReader = oProcess.StandardOutput
sOutput = oStreamReader.ReadToEnd()
End Using
TextBox4.Text = sOutput
Select Case sOutput
Case Is = "The machine is permanently activated."
TextBox4.Text = "activated"
End Select
the code is working okay but the result that appears on my textbox4 is : The machine is permanently activated. i need to take this result to case statement
Select Case sOutput
Case Is = "The machine is permanently activated."
TextBox4.Text = "activated"
all i need if i get The machine is permanently activated. status from cmd then show in textbox4 word ( activated )
It could be that the output contains a space or a line break at the end. Call Trim() on the string to remove any leading or trailing spaces and/or line breaks.
Select Case sOutput.Trim()

How do i read the output from a batch file in a vb program

thanks in advance i just want to know if theres a way to read the output from a running batch file in a vb.net program. Thanks!
As one commenter above mentions, you can run the batch file in a shell within your VB.NET program and then read the directed output. I have done this exactly in previous project.
Here is a code snippet which shows how you can do it:
Dim outputFile As String = """" & Path.GetTempFileName & """"
Dim batchCommand As String = """C:\Path\To\MyFile.bat"">" & outputFile
Dim cmdProcess As New Process
With cmdProcess
.StartInfo = New ProcessStartInfo("cmd.exe", "/C " & batchCommand)
With .StartInfo
.CreateNoWindow = True
.UseShellExecute = False
End With
.Start()
.WaitForExit()
End With
' This is the output from the batch file.
Dim batchOutput As String = My.Computer.FileSystem.ReadAllText(outputFile)

How to run batch commands with dynamic statements?

I am writing code in VB.NET 2.0 and want to run batch commands for FTP using FTP -s:filename command.
I have a Batch file FTP.TXT for FTP Upload. It has the following statements:
OPEN <FPT SERVER IP>
USERNAME
PASSWORD
ASC
CD FOLDERNAME
PUT D:\DRFT000009.TXT FTPDRFTIN.DRFT000009
BYE
I have to dynamically change the filename in the Batch File. Now either I can create a Batch file at runtime and then read it or I got a code to set the input stream of the Process object. But its not working as desired.
This code runs fine but here I read a static batch file FTP.TXT from the computer:
Public Sub FTP4()
Dim psi As ProcessStartInfo
Dim totalerror As String = ""
psi = New ProcessStartInfo()
psi.FileName = "FTP.EXE"
psi.Arguments = " -s:D:\FTP.TXT"
psi.RedirectStandardError = True
psi.RedirectStandardOutput = True
psi.CreateNoWindow = True
psi.WindowStyle = ProcessWindowStyle.Hidden
psi.UseShellExecute = False
Dim process As Process = process.Start(psi)
Dim error2 As String = process.StandardError.ReadToEnd()
totalerror = totalerror & error2
process.WaitForExit()
Response.Write(totalerror)
End Sub
But I want somehow to get the FTP done with custom file name for each request. This is what I tried which is not working:
Public Sub FTP5()
Dim totalerror As String = ""
Dim BatchScriptLines(6) As String
Dim process As New Process
process.StartInfo.FileName = "FTP.EXE"
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
BatchScriptLines(0) = "OPEN <FPT IP ADDRESS>"
BatchScriptLines(1) = "USERNAME"
BatchScriptLines(2) = "PASSWORD"
BatchScriptLines(3) = "ASC"
BatchScriptLines(4) = "CD SFCD40DAT"
BatchScriptLines(5) = "PUT D:\DRFT000006.TXT FTPDRFTIN.DRFT000006"
BatchScriptLines(6) = "BYE"
For Each ScriptLine As String In BatchScriptLines
InputStream.Write(ScriptLine & vbCrLf)
Next
End Using
Dim error2 As String = process.StandardError.ReadToEnd()
totalerror = totalerror & error2
process.WaitForExit()
Response.Write(totalerror)
End Sub
Please advise how I can get the "FTP -s:filename" command executed in this case. Basically I want to do something similar to single line batch file execution which I not able to do.
Being a simple text file with a clear format, you could rewrite the file passing the parameters that need to be dynamically changed
Public Sub FTP4()
' Of course I assume that, at this point your program knows the exact values '
' to pass at the procedure that rebuilds the file'
PrepareFTPFile("D:\DRFT000006.TXT", "USERNAME", "PASSWORD")
' Now you call the original code.....
Dim psi As ProcessStartInfo
Dim totalerror As String = ""
psi = New ProcessStartInfo()
psi.FileName = "FTP.EXE"
psi.Arguments = " -s:D:\FTP.TXT"
....
End Sub
Public Sub PrepareFTPFile(fileToUpload as String, username as string, userpass as string)
Using sw = new StreamWriter("D:\FTP.TXT", False)
sw.WriteLine("OPEN <FPT IP ADDRESS>")
sw.WriteLine(username)
sw.WriteLine(userpass)
sw.WriteLine("ASC")
sw.WriteLine("CD SFCD40DAT")
sw.WriteLine("PUT " + fileToUpload + " FTPDRFTIN." + Path.GetFileNameWithoutExtension(fileToUpdload))
sw.WriteLine("BYE")
End Using
End Sub