Kurt
Kurt

Reputation: 1897

Keep console window open after completion

I'm running a bat file and having the output displayed in the console window. Right now, I am having the bat file intentionally fail (bat file contains "STARET www.webaddress.com"). The error catching and everything works, but the console window closes immediately. I would like to keep it open, but so far my searching how to do so hasn't come up with any solutions.

The code I currently have:

Me.processStartInfo = New ProcessStartInfo("C:\Admin\PsTools\psexec.exe", "\\PCName -u domain\" & user & " -p " & pass & " pathtobatfile")
Me.processStartInfo.RedirectStandardError = True
Me.processStartInfo.RedirectStandardOutput = True
Me.processStartInfo.WindowStyle = ProcessWindowStyle.Hidden
Me.processStartInfo.UseShellExecute = False
Dim process As System.Diagnostics.Process = Nothing

'Start the process, which runs the bat file on the remote server
process = System.Diagnostics.Process.Start(Me.processStartInfo)
AddHandler process.OutputDataReceived, AddressOf OutputHandler
process.BeginOutputReadLine()
process.WaitForExit()

Dim errorresponse As DialogResult
   If process.HasExited And process.ExitCode <> 0 Then
      errorresponse = MessageBox.Show("There was an error. Exit code: " & process.ExitCode & _
                        ". Do you wish to view the log?", "Error", MessageBoxButtons.YesNo, MessageBoxIcon.Error)
        ElseIf process.HasExited And process.ExitCode = 0 Then
            MessageBox.Show("The update completed successfully.", "Success", MessageBoxButtons.OK)
        End If
        If errorresponse = DialogResult.Yes Then
          'To fill in later
        End If

And the event handler sub:

Private Shared Sub OutputHandler(ByVal sendingProcess As Object, ByVal output As DataReceivedEventArgs)
    Console.WriteLine(output.Data)
End Sub

I've also tried just doing synchronous output (using StreamReader and Console.Writeline with a Readline()), but that didn't work either.

Upvotes: 1

Views: 2152

Answers (2)

Maximus
Maximus

Reputation: 10847

Try to add at the end

set err=%ERRORLEVEL%
pause
exit %err%

Upvotes: 1

keyboardP
keyboardP

Reputation: 69362

Try adding pause at the end of the BAT file. Alternatively, if you're lauching the bat file via a cmd process, you can add the /k argument.

cmd /k pathToBatFile

Upvotes: 0

Related Questions