How to transfer the result of programmatically executable ScriptBlock?

My program executes custom script blocks, and I want it to return its result gradually (for example, if the script block works for a long time).

However, the ScriptBlock API does not seem to show anything related to the pipeline!

It has some functions that look the way I need them (InvokeWithPipe), but they are internal, and their arguments are internal. I would not want to resort to hacking here.

So, is there a way to access the scriptblock pipeline? Maybe some reliable workaround?

+6
powershell streaming
source share
1 answer

Here is the code that will add an extension method for ScriptBlock to output the stream, invoking a delegate for each output object. This is true streaming since objects are not copied to the collection. This is for PowerShell 2.0 or later.

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 } } 

Example:

 // 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}}); 

(updated 2011/3/7 with parameter support)

Hope this helps.

+8
source share

All Articles