2011-05-25 84 views
0

我正在计算机上运行一些命令,我​​希望它们输出一个单独的文本文件,如果命令无法运行。阅读控制台输出写出错误日志VB

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 

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

回答

0

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

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

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

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