在cmd.exe中执行sql语句时,我想获取外部文件上的错误级别,以便我可以进行进一步的编码。
我已经使用了ECHO命令,并且错误级别显示在提示符下,但是我想在外部文件上获取它 我的代码就是这样;
Dim strCmdText As String
strCmdText = "/C sqlcmd -S " & Server & " -d " & Databasename & " -i " & FileName & " -o " & ResultFile & " -V "
System.Diagnostics.Process.Start("CMD.exe", strCmdText)
这里的输出在Resultfile中返回,同样,我想返回错误级别。
答案 0 :(得分:0)
使用vb.net,在运行“ command.ExecuteNonQuery()”时使用try catch并将错误保存到txt。使用cmd是否有充分的理由?
就像..
Try
command.ExecuteNonQuery()
Catch (Ex As Exception)
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("c:\test.txt", True)
file.WriteLine(ex.message)
file.Close()
End try
如果您仍然想使用RedirectStandardOutput,请看一下在线程中也发现的内容:
Imports System.Diagnostics
Imports System.IO
Private CurrentProcessID As Integer = -1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
StartProcess("C:\Windows\System32\tracert.exe", "stackoverflow.com")
End Sub
Private Sub StartProcess(FileName As String, Arguments As String)
Dim MyStartInfo As New ProcessStartInfo() With {
.FileName = FileName,
.Arguments = Arguments,
.WorkingDirectory = Path.GetDirectoryName(FileName),
.RedirectStandardError = True,
.RedirectStandardOutput = True,
.UseShellExecute = False,
.CreateNoWindow = True
}
Dim MyProcess As Process = New Process() With {
.StartInfo = MyStartInfo,
.EnableRaisingEvents = True,
.SynchronizingObject = Me
}
MyProcess.Start()
MyProcess.BeginErrorReadLine()
MyProcess.BeginOutputReadLine()
CurrentProcessID = MyProcess.Id
AddHandler MyProcess.OutputDataReceived,
Sub(sender As Object, e As DataReceivedEventArgs)
If e.Data IsNot Nothing Then
BeginInvoke(New MethodInvoker(
Sub()
RichTextBox1.AppendText(e.Data + Environment.NewLine)
RichTextBox1.ScrollToCaret()
End Sub))
End If
End Sub
AddHandler MyProcess.ErrorDataReceived,
Sub(sender As Object, e As DataReceivedEventArgs)
If e.Data IsNot Nothing Then
BeginInvoke(New MethodInvoker(
Sub()
RichTextBox1.AppendText(e.Data + Environment.NewLine)
RichTextBox1.ScrollToCaret()
End Sub))
End If
End Sub
AddHandler MyProcess.Exited,
Sub(source As Object, ev As EventArgs)
MyProcess.Close()
If MyProcess IsNot Nothing Then
MyProcess.Dispose()
End If
End Sub
End Sub
答案 1 :(得分:0)
如果使用echo命令提示您为什么不使用
@echo message> c:\test.txt
您也可以使用
if errorlevel 1 goto function
:Function
@echo message> c:\test.txt
我想这就是你想要的? 代替输出而不是使用echo命令写入文件?