簡體   English   中英

如何通過運行PowerShell腳本顯示實時輸出?

[英]How to show real-time output by running a PowerShell Script?

我試圖從VB運行powershell腳本,我想看到腳本在控制台應用程序中運行時的輸出。 使用我的腳本(如下所示),當我從powershell運行時,它顯示“命令睡眠啟動”,然后等待5秒,然后顯示其他文本。

但是,當我從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)

您是否考慮過使用System.Windows.Automation命名空間以編程方式執行PowerShell運行空間而不是啟動該進程? 然后,您可以將記錄器對象傳遞給管道並記錄到它,實時顯示消息。

這是一個簡單的片段,用於在VB.NET中啟動Runspace

    ' 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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM