基本上,我的目标是捕获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();
我可以成功运行脚本,但是与进度相关的事件似乎永远不会触发。我想念什么吗?
答案 0 :(得分:0)
感谢@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
会创建一个我已成功订阅的本地运行空间。