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

2024-01-21

我编写了一段代码(用 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 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过代码调用时获取 Powershell 命令的输出 的相关文章

随机推荐