【发布时间】: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