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

时间:2015-12-21 14:30:15

标签: c# powershell azure

我编写了一段代码(在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 (i.e. during command execution) 
 foreach (var psObject in results)
 {
     System.Diagnostics.Debug.Write(psObject.BaseObject.ToString());
 }

请指导是否可以从Powershell检索实时输出。

1 个答案:

答案 0 :(得分:17)

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

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

方式更简单。

现在,PowerShell类通过Streams property公开了各种非标准输出流(详细,调试,错误等) - 包括进度流 - 所以你可以订阅它,比如这样:

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);
    }
}

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

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