I am looking for almost similar solution. The scenario is same. I have parallel for each loop in c#.net. It calls 2 functions before actually hits the powershell code. The code snippet is below.
My question is, what is correct approach to call powershell script file in parallel using run space from c# code. Currently the issue is that powershell is in wait state indefinitely.
Please let me know improved or right way. I am not clear on the code you gave as example above, especially creating runspace pool and assigning to PS object. How or when do you call RemoteCommandInvoker(). I understand its a constructor, is that suffice. ?
My code snippet. The code is called from Prallel.ForEach. Here we pass IPdress and machine name. The script file is same.
public string ExecuteCommandDirect(string IpAddress, string machineName, string logFilePath, string powerShellPath, string PSLogFilePath) { String FullPsFilePath = powerShellPath; // path of powershell script file; String PsParameters = FullPsFilePath + " " + IpAddress + " " + machineName + " " + PSLogFilePath;
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
//Console.WriteLine("Create pipeline & add commands....");
// Create pipeline and add commands
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(PsParameters);
// Execute Script
Collection<PSObject> results = new Collection<PSObject>();
AWSlogging.WriteLog("Invoking Script....", logFilePath);
try
{
results = pipeline.Invoke();
}
catch (Exception ex)
{
results.Add(new PSObject((object)ex.Message));
}
// Close runspace
runspace.Close();
runspace.Dispose();
//Console.WriteLine("Completed.Run Space closed...");
AWSlogging.WriteLog("Completed.Run Space closed...", logFilePath);
//Script results to string
StringBuilder stringBuilder = new StringBuilder();
//Console.WriteLine("Output....Start");
AWSlogging.WriteLog("Output....Start", logFilePath);