2011-05-25 118 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