如何通过运行PowerShell脚本显示实时输出?

时间:2012-03-01 18:48:36

标签: .net vb.net powershell

我正在尝试从VB运行powershell脚本,我希望看到脚本在控制台应用程序中运行时的输出。使用我的脚本(如下所示),当我从powershell运行时,它会显示“Command Sleep Starting”,然后等待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)

1 个答案:

答案 0 :(得分:4)

您是否考虑过使用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()