如何通过运行PowerShell脚本来显示实时输出?
我想从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)
你有没有考虑执行的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()
同意这一点。而不是调用PowerShell.exe,只需使用API :-) – 2012-03-02 01:56:30
我同意上述方法是运行powershell命令的方式,但我很抱歉,我的问题不是这样。我想知道是否可以在脚本运行时显示增量输出。这种方法会显示增量输出吗? – Mitul 2012-03-02 14:22:11
如果您将记录器对象传递给脚本,然后用调用将记录输出调用替换为记录器,那么从记录器显示实时数据的能力将取决于它的实现。一个例子就是一个TraceListener模型,您可以在其中订阅您希望的任何监听器,并无论如何都可视化日志记录输出。 – 2012-03-02 15:28:00
[有人](http://stackoverflow.com/questions/8740118/interact-with-powershell-process-called-简单片断from-java-application/8740564#8740564)试图用Java来做到这一点。我不确定标准输出可以被读取,直到进程退出。 – 2012-03-01 22:07:46