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>(),
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.
x0n
source share