Well, that's the basics of how to execute PowerShell from within C#. However, if you're doing this millions of times, you may find that it's much faster to run the script once, keep an open runspace, and then run the function multiple times. That way you're not forcing PowerShell to parse and compile the script every time through the loop. Something along these lines:
using (var runspace = RunspaceFactory.CreateRunspace()) { using (var powerShell = PowerShell.Create()) { powerShell.Runspace = runspace; powerShell.AddScript(PsScript); powerShell.Invoke(); } foreach (var thingy in thingies) { using (var powerShell = PowerShell.Create()) { powerShell.Runspace = runspace; powerShell.AddCommand("My-Function"); powerShell.AddParameter("ParamA", varA); powerShell.AddParameter("ParamB", varB); powerShell.AddParameter("ParamC", varC); powerShell.AddParameter("ParamD", varD); var results = powerShell.Invoke(); // Do whatever with results } } }
(Note: I wrote this in Notepad, and haven't tested it. It probably doesn't work as-is.)