2012-03-01 531 views
1

我想從VB運行powershell腳本,我希望看到腳本輸出在控制檯應用程序內運行。使用我的腳本(如下所示)從PowerShell運行時,它顯示「Command Sleep Starting」,然後等待5秒鐘,然後顯示其他文本。如何通過運行PowerShell腳本來顯示實時輸出?

但是,當我從VB.NET程序運行時,執行等待5秒鐘並立即轉儲所有文本輸出。它不執行第一個寫入 - 輸出命令,然後等待,然後輸出它應該。

Write-Output "Command Sleeping Starting" 
Start-Sleep -Seconds 5 
Write-Output "Command ran successfully" 

當我從VB .Net程序運行腳本時,如何顯示實時執行輸出的任何想法?

以下更多信息是我使用的代碼。

  Dim start As New ProcessStartInfo 
      Dim ScriptsFolder As String = GetKeyValue("ScriptsFolder") 
      Console.WriteLine(ScriptsFolder.ToString()) 
      start.FileName = "powershell.exe" 
      start.Arguments = ScriptsFolder + "\" + ScriptFile 
      start.UseShellExecute = False 
      start.RedirectStandardOutput = True 
      start.RedirectStandardError = True 

      Dim myproc As New Process 
      myproc.StartInfo = start 
      myproc.Start() 
      Dim so As System.IO.StreamReader 
      Dim se As System.IO.StreamReader 
      se = myproc.StandardError 
      so = myproc.StandardOutput 
      myproc.WaitForExit() 
      Console.WriteLine(so.ReadToEnd) 
      Console.WriteLine(se.ReadToEnd) 
+0

[有人](http://stackoverflow.com/questions/8740118/interact-with-powershell-process-called-簡單片斷from-java-application/8740564#8740564)試圖用Java來做到這一點。我不確定標準輸出可以被讀取,直到進程退出。 – 2012-03-01 22:07:46

回答

4

你有沒有考慮執行的PowerShell運行空間編程方式使用System.Windows.Automation命名空間,而不是啓動進程?然後,您可以將一個記錄器對象傳遞到管道並記錄到它,實時顯示消息。

下面是在VB.NET紡紗了運行空間

' create Powershell runspace 
    Dim MyRunSpace As Runspace = RunspaceFactory.CreateRunspace() 

    ' open it 
    MyRunSpace.Open() 

    ' create a pipeline and feed it the script text 
    Dim MyPipeline As Pipeline = MyRunSpace.CreatePipeline() 

    MyPipeline.Commands.AddScript(scriptText) 

    ' pass in a logger object you can use instead of Write-Output 
    MyPipeline.Runspace.SessionStateProxy.SetVariable("logger", SomeLoggerObject) 

    ' execute the script 
    Dim results As Collection(Of PSObject) = MyPipeline.Invoke() 

    ' close the runspace 
    MyRunSpace.Close() 
+0

同意這一點。而不是調用PowerShell.exe,只需使用API​​ :-) – 2012-03-02 01:56:30

+0

我同意上述方法是運行powershell命令的方式,但我很抱歉,我的問題不是這樣。我想知道是否可以在腳本運行時顯示增量輸出。這種方法會顯示增量輸出嗎? – Mitul 2012-03-02 14:22:11

+0

如果您將記錄器對象傳遞給腳本,然後用調用將記錄輸出調用替換爲記錄器,那麼從記錄器顯示實時數據的能力將取決於它的實現。一個例子就是一個TraceListener模型,您可以在其中訂閱您希望的任何監聽器,並無論如何都可視化日誌記錄輸出。 – 2012-03-02 15:28:00

相關問題