【问题标题】:Getting Write-Progress -PercentComplete status from within C#从 C# 中获取 Write-Progress -PercentComplete 状态
【发布时间】:2018-06-28 02:45:36
【问题描述】:

基本上,我的目标是在我的 C# 实例中捕获 Powershell 脚本的进度。我发现这个answer 是相关的,但它不起作用(输出控制台中没有任何内容)。这是我使用已接受答案中的建议的实现。

TEST.ps1

Write-Progress -Activity "Finding user" -CurrentOperation "TEST1" -PercentComplete 1
#Some task
Write-Progress -Activity "Finding user" -CurrentOperation "TEST2" -PercentComplete 2
#Some other task
Write-Progress -Activity "Finding user" -CurrentOperation "TEST3" -PercentComplete 3
#Some other task
...

TEST.cs

//creating PS instance
PowerShell ps = PowerShell.Create();

//creating a runspace
Runspace runspace = RunspaceFactory.CreateRunspace();

//Associating the runspace
ps.Runspace = runspace;

//creating the pipeline
Pipeline pipeline = ps.Runspace.CreatePipeline();
ps.Runspace.Open();

//Feeding the script to the pipeline
Command myCommand = new Command("TEST.ps1");
pipeline.Commands.Add(myCommand);

ps.Streams.Progress.DataAdded += (sender, eventargs) => {
    PSDataCollection<ProgressRecord> progressRecords = (PSDataCollection<ProgressRecord>)sender;
    System.Diagnostics.Debug.WriteLine("Progress is {0} percent complete", progressRecords[eventargs.Index].PercentComplete);
};

// execute the script
results = pipeline.Invoke();

我成功运行脚本没有问题,但与进度相关的事件似乎永远不会触发。我错过了什么吗?

【问题讨论】:

  • 尝试使用PowerShell对象而不是自己创建Pipeline
  • @PetSerAl 添加了一个解决方案,你把我带到了那里。谢谢!

标签: c# powershell


【解决方案1】:

感谢@PetSerAl 引导我找到解决方案。

using (PowerShell ps = PowerShell.Create())
{
    ps.Streams.Progress.DataAdded += (sender, eventargs) =>
    {
        PSDataCollection<ProgressRecord> progressRecords = (PSDataCollection<ProgressRecord>)sender;
        System.Diagnostics.Debug.WriteLine("Progress is {0} percent complete", progressRecords[eventargs.Index].PercentComplete);
    };
    Command myCommand = new Command("TEST.ps1");
    ps.Commands.AddCommand(myCommand);

    // execute the script
    results = ps.Invoke();
}

基本上,使用ps 对象是解决方案。我的猜测是我没有在正确的运行空间上注册我的事件。现在调用 ps 创建一个我成功订阅的本地运行空间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-28
    • 1970-01-01
    • 2012-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    相关资源
    最近更新 更多