我的程序执行用户指定的脚本 block ,我希望它以增量方式返回其输出(例如,如果脚本 block 运行很长时间)。
但是,ScriptBlock 的 API 似乎没有公开任何与管道相关的内容!
它有一些看起来像是我需要的函数(InvokeWithPipe),但它们是内部的,它们的参数是内部类型的。我不想在这里求助于反射(reflection)。
那么,有没有办法访问脚本 block 的管道?也许某种强大的解决方法?
最佳答案
下面是一些代码,它将向 ScriptBlock 添加扩展方法以流式输出,为每个输出对象调用一个委托(delegate)。这是真正的流式传输,因为对象没有在集合中备份。这适用于 PowerShell 2.0 或更高版本。
public static class ScriptBlockStreamingExtensions {
public static void ForEachObject<T>(
this ScriptBlock script,
Action<T> action,
IDictionary parameters) {
using (var ps = PowerShell.Create()) {
ps.AddScript(script.ToString());
if (parameters != null) {
ps.AddParameters(parameters);
}
ps.Invoke(Enumerable.Empty<object>(), // input
new ForwardingNullList<T>(action)); // output
}
}
private class ForwardingNullList<T> : IList<T> {
private readonly Action<T> _elementAction;
internal ForwardingNullList(Action<T> elementAction) {
_elementAction = elementAction;
}
#region Implementation of IEnumerable
// members throw NotImplementedException
#endregion
#region Implementation of ICollection<T>
// other members throw NotImplementedException
public int Count {
get {
return 0;
}
}
#endregion
#region Implementation of IList<T>
// other members throw NotImplementedException
public void Insert(int index, T item) {
_elementAction(item);
}
#endregion
}
}
例子:
// execute a scriptblock with parameters
ScriptBlock script = ScriptBlock.Create("param($x, $y); $x+$y");
script.ForEachObject<int>(Console.WriteLine,
new Dictionary<string,object> {{"x", 2},{"y", 3}});
(2011/3/7 更新,支持参数)
希望这可以帮助。
关于.net - 如何流式传输以编程方式执行的 ScriptBlock 的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5183389/