I need to execute some cmdlets in a remote powershell session, in a certain order: ex. if this distribution-group exists then add this user to the group but I keep getting errors about runspace state or that I created too many runspaces and I have to wait some time. I can't use a runspace pool because for each session I need to get the result of a cmdlet before executing other cmdlets.
I have tried to execute the cmdlets block script (two or three chdlets that depend on the result of the others) in the same runspace but I get the invalid runspace state because the runspace is not open. I do dispose the runspace after finithing the cmdlet block script and I do dispose the powershell session too.
After searching on this site for some answers I read someone's answer in a related question, where he said that the runspace and powershell session soud be discarded after each invoke and created again, but after a short time I get an error saying I cannot create more runspaces.
Collection<PSObject> resultado = new Collection<PSObject>();
try
{
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri(LiveId), SchemaUri, Credenciales);
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;
Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);
if (runspace != null && Credenciales != null)
{
PowerShell PS = PowerShell.Create();
PS.Runspace = runspace;
runspace.Open();
using (Pipeline pipeline = runspace.CreatePipeline())
{
Command cmd = new Command(comando);
foreach (KeyValuePair<string, string> parametro in parametros)
{
cmd.Parameters.Add(parametro.Key, parametro.Value);
}
pipeline.Commands.Add(cmd);
resultado = pipeline.Invoke();
}
runspace.Close();
runspace.Dispose();
PS.Dispose();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace + "/" + comando + parametros);
}
How shoud I correctly manage the runspace so I can make sure that every cmdlet block script is executed correctly?
Thank you very much!!!