通过代码调用时获取Powershell命令的输出

我编写了一段代码(在C#中),使用System.Management.Automation执行Powershell脚本(特别是Azure PowerShell)。 powershell脚本基本上在Azure上的容器中上传vhd,当通过azure Powershell手动输入命令时,该容器显示上载进度和经过的时间等。 通过代码一切正常但我想在命令执行期间获得命令的结果/输出(即上传进度,时间已过去)(即pipeline.invoke(); )这里是代码:

  RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration); runspace.Open(); RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); Pipeline pipeline = runspace.CreatePipeline(); Command myCommand = new Command(scriptPath); foreach (var argument in arguments) { myCommand.Parameters.Add(new CommandParameter(argument.Key, argument.Value)); } pipeline.Commands.Add(myCommand); var results = pipeline.Invoke(); // i want to get results here (ie during command execution) foreach (var psObject in results) { System.Diagnostics.Debug.Write(psObject.BaseObject.ToString()); } 

如果可以从Powershell检索实时输出,请指导。

除非您的目标是PowerShell 1.0,否则无需手动设置您的运行空间和管道,而是创建PowerShell类的实例:

 PowerShell psinstance = PowerShell.Create(); psinstance.AddScript(scriptPath); var results = psinstance.Invoke(); 

方式更简单。


现在, PowerShell类通过Streams属性公开各种非标准输出流(详细,调试,错误等) – 包括Progress Stream – 因此您可以订阅它,如下所示:

 psinstance.Streams.Progress.DataAdded += myProgressEventHandler; 

然后在你的事件处理程序中:

 static void myProgressEventHandler(object sender, DataAddedEventArgs e) { ProgressRecord newRecord = ((PSDataCollection)sender)[e.Index]; if (newRecord.PercentComplete != -1) { Console.Clear(); Console.WriteLine("Progress updated: {0}", newRecord.PercentComplete); } } 

作为示例,这里是上面显示的事件处理程序,同时运行一个示例脚本,该脚本将进度信息(下面发布的示例脚本)写入一个简单的控制台应用程序中:

readProgress

测试Progress.ps1

 function Test-Progress { param() Write-Progress -Activity 'Testing progress' -Status 'Starting' -PercentComplete 0 Start-Sleep -Milliseconds 600 1..10 |ForEach-Object{ Write-Progress -Activity "Testing progress" -Status 'Progressing' -PercentComplete $(5 + 6.87 * $_) Start-Sleep -Milliseconds 400 } Write-Progress -Activity 'Testing progress' -Status 'Ending' -PercentComplete 99 Start-Sleep -Seconds 2 Write-Progress -Activity 'Testing progress' -Status 'Done' -Completed } Test-Progress