run 2 seperate cmd commands from vb forms appliaction - vb.net

i want my program to open cmd , change directory and then do the command : "copy /B file1 file2 output"
this is what i have at the moment. but all that happens is a cmd window flashes for a second but no file gets created
Dim cmd1 As String
Dim cmd2 As String
cmd1 = "cd " & FolderFromFileName(imagename)
cmd2 = "copy /B " & NameOnlyFromFullPath(imagename) & "+" & "TEMP.txt" & " " & TextBox1.Text
Shell("cmd /c" & " " & cmd1 & " " & cmd2, AppWinStyle.NormalFocus)
please help, thanks :)

Do you really need to have a command prompt appear? You could do all this without a separate process by using the system.io library. If you really need the cmd prompt you can create a process.
Dim NewProcess = New Process
' a new process is created
NewProcess.StartInfo.UseShellExecute = False
' redirect IO
' PVWCmd.StartInfo.RedirectStandardOutput = True
' PVWCmd.StartInfo.RedirectStandardError = True
' PVWCmd.StartInfo.RedirectStandardInput = True
' don't even bring up the console window
NewProcess.StartInfo.CreateNoWindow = False
' executable command line info
NewProcess.StartInfo.FileName = "cmd"
NewProcess.StartInfo.WorkingDirectory = "C:\"
' NewProcess.StartInfo.Arguments = +" > """ + "LogFile.log" + """ 2>&1"
NewProcess.Start()

Related

How can I see the results and how can the windows Close

I have this code, and I´m calling one Java program to pass the aurguments, that I select in VB.
My issues is:
The cmd windows open, but I can't see what the program is doing, I only see on the window the arguments that are pass, and when finish, the window don't close.
enter image description here
and when program stop, the windows don't close.
enter image description here
This is the result if I run by command line
enter image description here
txbSendCommand.Text = "java -jar FACTEMICLI-2.5.16-33194-cmdClient.jar " & "-i " & TextBox1.Text & "" & " -n " & stNIF & " -p " & stPassword & " -a " & iAno & " -m " & iMes & " -op " & stvalidar & stFicheiroEscolhido & " -o c:\saft\outputfile.xml"
Dim stcaminhoexterno As String
If stErrorMessage = False Then
Dim app As New ProcessStartInfo("cmd.exe") With {.RedirectStandardInput = True, .UseShellExecute = False, .CreateNoWindow = False}
Dim myProcess As New Process
myProcess = Process.Start(app)
Dim arguments As String = txbSendCommand.Text
myProcess.StandardInput.WriteLine(arguments)
myProcess.Close()
End If
How can I see the results in the external windows, or better even in a windows or something that I can have in the form.
How Can the window close after the process is done

WaitForExit with CMD option "/c"

I've written code in VB to run a CMD command, where the output is stored to a text file. This output is then needed for the program, so the program needs to wait until the CMD command has finished before continuing. I am using
Dim wait As Process = Process.Start(psi)
wait.WaitForExit()
To make sure the process exits before the code continues, but now that I've done that, the "/c" option in the process info is no longer working. The process info is as follows:
Dim psi As New ProcessStartInfo With {
.FileName = "Cmd",
.Arguments = "/c " & completedCom & " > " & oPath
}
I do not understand why the "/c" option would fail all of a sudden.
Spaces would be an example of one problem. Use quotes around your commands to help with that:
Dim psi As New ProcessStartInfo With {
.FileName = "Cmd",
.Arguments = "/c """ & completedCom & """ > """ & oPath & """"
}
The preferred method of calls to process would be to directly call the exec, rather than launching a cmd. In that case, you would have to capture the standard output asynchronously and write it to a file though.

Running and saving command output using VBA

I am trying to run shell commands from VBA and get output into a csv file. Below is the code I am using:
Dim wsh as Object
Set wsh = VBA.CreateObject("WScript.Shell")
plink_path="C:\plink.exe"
key_path="putty key path"
pass_query="select * from test"
command1 = Replace(plink_path & " hadoop#11.11.11.11 -i " & key_path & " mysql -uuser -ppass -e 'use radar;" & pass_query & "'", Chr(10), " ")
wsh.Run command1 & ">E:/anurag.csv", 0, True
But I am not able to view output file in the E drive. When I run the above command manually from a cmd prompt I do get an output in the E drive.
Two thoughts:
Try E:\anurag.csv instead of E:/anurag.csv
Use cmd to invoke plink, since cmd usually processes the redirections. Replace the wsh.Run line with:
command1 = command1 & ">E:\anurag.csv"
command1 = "cmd /c """ & command1 & """"
wsh.Run command1, 0, True
The first line completes the command you wanted to execute and the second wraps it in a cmd /c call.
If this doesn't work, try changing /c above to /c /s per this answer.
YMMV - not tested

The term 'connect-nacontroller' is not recognized as the name of a cmdlet, function, script file, or operable program

Doesn't it figure. Moments after I post this, I finally get it to work. I'll post what I did just in case anyone else has this issue in the futures. It's a big oversight for me!
Right before the username line, I added this line:
"Import-Module DataOnTap" & Environment.NewLine & _**
I'm trying to run a PowerShell script from within VB.Net 2010 code. When I run the code in PowerShell, it runs fine. When I run it from within VS2010, I get the error:
"The term 'connect-nacontroller' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again."
The error occurs when it gets to the "Dim results As Collection(Of PSObject) = MyPipeline.Invoke()" line.
Here is my code (I changed the username and password and will be changing how it comes into the code once I get it to work. I also changed the name of the volume):
Protected Sub ExecuteCode_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
resultBox.Text = RunScript(powerShellCodeBox.Text)
End Sub
Private Function RunScript(ByVal scriptText As String) As String
Dim MyRunSpace As Runspace = RunspaceFactory.CreateRunspace()
MyRunSpace.Open()
Dim MyPipeline As Pipeline = MyRunSpace.CreatePipeline()
Dim userName As String = "abc"
Dim password As String = "123"
Dim myscript As String = "$username = " & Chr(34) & userName & Chr(34) & Environment.NewLine & _
"$password = ConvertTo-SecureString " & Chr(34) & password & Chr(34) & " -AsPlainText -Force" & Environment.NewLine & _
"$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userName,$password" & Environment.NewLine & _
"connect-nacontroller mydrive -credential $cred" & Environment.NewLine
MyPipeline.Commands.AddScript(myscript)
MyPipeline.Commands.Add("Out-String")
Dim results As Collection(Of PSObject) = MyPipeline.Invoke()
MyRunSpace.Close()
Dim MyStringBuilder As New StringBuilder()
For Each obj As PSObject In results
MyStringBuilder.AppendLine(obj.ToString())
Next
Return MyStringBuilder.ToString()
End Function
Right before the username line, I added this line:
"Import-Module DataOnTap" & Environment.NewLine & _**

VB piping STDOUT from cmd.exe output to to write to textbox

I'm trying to adapt a VBscript that runs the QWINSTA command against a text file I've defined as an array and displays the results in a text file.
after looking at numerous examples on Stack and other sites this is my latest iteration, that displays everything except the STDOUT, which is really what I'm after, not sure if it's an issue with how I'm calling the command piping the output or what. I'm also passing two variables as arguments to complicate matters :)
The Text file that stdout is piped to is empty after the FOR Loop completes
I may be going the long way about this, most of my past experience with this is in BATCH
For Each server In RemotePC
'The Query is launched
Dim Query As New ProcessStartInfo
Query.WorkingDirectory = "c:\"
Query.Arguments = server & " " & profile & " >C:\Windows\Temp\SFOUT.txt"
Query.FileName = "QWINSTA"
Query.WindowStyle = ProcessWindowStyle.Hidden
Process.Start(Query)
'Call Shell("QWINSTA /SERVER:" & server & " " & profile & " >C:\Windows\Temp\SFOUT.txt", vbHidden, Timeout:=5000)
Dim SFOUT As New IO.StreamReader("C:\windows\temp\SFOUT.txt")
'Results are Echoed to TextboxResults
TextBoxResults.Text &= "__________________________________________________________" & ControlChars.CrLf
TextBoxResults.Text &= server & ControlChars.CrLf
TextBoxResults.Text &= SFOUT.ReadToEnd & ControlChars.CrLf
SFOUT.Close()
Next
Here is what the working code in VBscript looks like
For Each server In RemotePC
Dim WshShell, oExec
Set WshShell = CreateObject("WScript.Shell")
Set StrDir = "QWINSTA /SERVER:" & server & " " & profile
'The Query is launched
Set oExec = WshShell.Exec(StrDir)
'We wait for the end of process
Do While oExec.Status = 0
WScript.Sleep 500
Loop
'We scan and only display the command output of commands without NULL output
Do While oExec.StdOut.AtEndOfStream <> True
Results.WriteLine("__________________________________________________________")
Results.WriteLine(server)
Results.WriteLine oExec.StdOut.ReadLine
Loop
NEXT
Any help is appreciated
#Nilpo
this is what I get back
SESSIONNAME USERNAME ID STATE TYPE DEVICE
console Matt 1 Active
I've built something similar to this using QWINSTA and piping the output in batch and it works flawlessly, just having issues adapting this.
here's the last thing I tried I tried to simplify things by calling something as basic as notepad.exe, and even trying to define the environment variable thinking it's not reading %PATH%, in reply to #Nilpo
Dim Query As New Process
Query.StartInfo.FileName = "notepad.exe"
'Query.StartInfo.Arguments = server & " " & profile & " >C:\Windows\Temp\SFOUT.txt"
Query.StartInfo.UseShellExecute = False
Query.StartInfo.RedirectStandardOutput = True
Query.StartInfo.WindowStyle = ProcessWindowStyle.Normal
Environment.SetEnvironmentVariable("PATH", "%PATH%;" & "C:\Windows\System32\notepad.exe")
Query.Start()
You should have a space after the output redirection.
Query.Arguments = server & " " & profile & " >C:\Windows\Temp\SFOUT.txt"
Should be
Query.Arguments = server & " " & profile & " > C:\Windows\Temp\SFOUT.txt"
That being said, the only thing I can see that may not work is here.
Query.WorkingDirectory = "c:\"
Query.Arguments = server & " " & profile & " >C:\Windows\Temp\SFOUT.txt"
Query.FileName = "QWINSTA"
Query.WindowStyle = ProcessWindowStyle.Hidden
Process.Start(Query)
I'm not sure that you can use arguments in this fashion. Your output redirection is being read as a literal argument when it's really not. In a command line environment it's interpreted as a separate command, not an argument to the first command. It's very similar to piping in that manner. Supplying this as an argument in your code probably won't work as expected. You may want to go back to the Call Shell method. That will execute the command as if it were on the command line.
[Edit]
I was correct. Here is the proper way to do this using your method.
Query.WorkingDirectory = "c:\"
Query.Arguments = server & " " & profile & " >C:\Windows\Temp\SFOUT.txt"
Query.FileName = "QWINSTA"
Query.WindowStyle = ProcessWindowStyle.Hidden
'Redirect output
Query.UseShellExecute = False
Query.RedirectStandardOutput = True
Process.Start(Query)
'Read the output
Dim output As String = Process.StandardOutput.ReadToEnd
' wait for the process to terminate
Process.WaitForExit