使用 sqlcmd 时将错误级别返回到外部文件

Returning error level to an external file when working on sqlcmd

我想在 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)

这里的输出是 return 在结果文件中编辑的,同样我想 return 错误级别。

Using 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", "whosebug.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

如果使用 echo 命令提示你为什么不使用

@echo message> c:\test.txt 

你也可以使用

if errorlevel 1 goto function

:Function
@echo message> c:\test.txt

我想这就是你想要的? 可以使用 echo 命令而不是输出来写入文件?