读取控制台输出以写出错误日志VB

时间:2011-05-25 15:36:30

标签: vb.net visual-studio-2010

我正在计算机上运行一些命令,如果命令无法运行,我想让它们输出一个单独的文本文件。

For Each strUserName As String In strLines
        Dim ReplaceCommand As String = sCommand.Replace("*", strUserName).Replace("$$$", saveFileDialog3.FileName & ".txt").Replace("###", exeSearch)
        Shell("cmd.exe /c" & ReplaceCommand, AppWinStyle.Hide, True, )


        ' If Command Cannot Execute, List Why and Move onto Next Command
            Using swrr As New StreamWriter(File.Open(ErrorLog, FileMode.OpenOrCreate))
                If Console.Readline = "blahblah" Then swrr.WriteLine("FAIL") Else swrr.WriteLine("PASS")
        End Using
Next

我是否在正确的轨道上?我得到一个文本文件的输出,但它只是一行,总是说PASS。

1 个答案:

答案 0 :(得分:0)

有几件事情:你每次想要为它写一行时都要创建一个新的StreamWriter,而不是创建一个,然后在需要时写入它。你仍然使用的是真正基本的shell,并不适合你需要的东西。你应该真的使用一个过程。

我已经编写了一个函数供您执行而不是使用shell,它会将命令执行的输出返回给ConsoleOutput变量,然后您可以检查输出字符串。

最后,您应该使用String.Format而不是replace来为命令运行创建正确的字符串。例如:

    Dim FirstName As String = "Jay"
    Dim Age As String = "twenty"
    Dim Greeting As String = String.Format("Hello {0}, I know you're {1} years old", FirstName, Age)
    ' Greetings value would be "Hello Jay, I know you're twenty years old"

所以调整下面的内容,特别是Args变量,使用STRING.FORMAT函数:)

 Sub DoWork()

        Dim ConsoleOutput As String = String.Empty

        Using swrr As New StreamWriter(ErrorLog, True)

            For Each strUserName As String In StrLines

                ConsoleOutput = GetCMDOuput(strUserName, saveFileDialog3.FileName, exeSearch)

                ' If Command Cannot Execute, List Why and Move onto Next Command
                If ConsoleOutput = "blahblah" Then swrr.WriteLine("FAIL") Else swrr.WriteLine("PASS")

            Next

        End Using

    End Sub

    Function GetCMDOuput(ByVal strUserName As String, ByVal strFileName As String, ByVal strExeSearch As String) As String

        Dim Args As String = String.Format("/c -paramzero {0} -paramone {1} -paramtwo {2}", strUserName, strFileName, strExeSearch)

        Dim CMD As New Process
        CMD.StartInfo.FileName = "cmd.exe"
        CMD.StartInfo.Arguments = Args
        CMD.StartInfo.UseShellExecute = False
        CMD.StartInfo.RedirectStandardInput = True
        CMD.StartInfo.RedirectStandardOutput = True
        CMD.StartInfo.CreateNoWindow = True
        CMD.Start()

        Dim retval As String = CMD.StandardOutput.ReadToEnd

        CMD.WaitForExit()

        Return retval

    End Function