我编写了一段代码(在C#中)来执行Powershell脚本(特别是Azure PowerShell)System.Management.Automation
.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 (i.e. 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
属性,所以你可以订阅它,就像这样:
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); } }
作为示例,这里是上面显示的事件处理程序,同时运行一个示例脚本,该脚本将进度信息(下面发布的示例脚本)写入一个简单的控制台应用程序中:
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