除非您的目标是 PowerShell 1.0,否则无需手动设置运行空间和管道,创建一个实例PowerShell class https://msdn.microsoft.com/en-us/library/system.management.automation.powershell(v=vs.85).aspx反而:
PowerShell psinstance = PowerShell.Create();
psinstance.AddScript(scriptPath);
var results = psinstance.Invoke();
简单多了。
现在PowerShell
类公开各种非标准输出流(详细、调试、错误等) - 包括进度流 - 通过Streams财产 https://msdn.microsoft.com/en-us/library/system.management.automation.psdatastreams(v=vs.85).aspx这样你就可以订阅它,如下所示:
psinstance.Streams.Progress.DataAdded += myProgressEventHandler;
然后在你的事件处理程序中:
static void myProgressEventHandler(object sender, DataAddedEventArgs e)
{
ProgressRecord newRecord = ((PSDataCollection<ProgressRecord>)sender)[e.Index];
if (newRecord.PercentComplete != -1)
{
Console.Clear();
Console.WriteLine("Progress updated: {0}", newRecord.PercentComplete);
}
}
作为示例,下面是上面显示的事件处理程序的实际操作,同时运行一个示例脚本,该脚本在一个简单的控制台应用程序中写入进度信息(下面发布的示例脚本):
测试进度.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