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!!!
I found this template Runspaces Simplified (as much as possible) by Chrissy LeMaire to be extremely helpfull, all you have to do is to pass scriptblock
Below is the template
# BLOCK 1: Create and open runspace pool, setup runspaces array with min and max threads
$pool = [RunspaceFactory]::CreateRunspacePool(1, [int]$env:NUMBER_OF_PROCESSORS+1)
$pool.ApartmentState = "MTA"
$pool.Open()
$runspaces = @()
# BLOCK 2: Create reusable scriptblock. This is the workhorse of the runspace. Think of it as a function.
$scriptblock = {
Param (
[string]$connectionString,
[object]$batch,
[int]$batchsize
)
$bulkcopy = New-Object Data.SqlClient.SqlBulkCopy($connectionstring,"TableLock")
$bulkcopy.DestinationTableName = "mytable"
$bulkcopy.BatchSize = $batchsize
$bulkcopy.WriteToServer($batch)
$bulkcopy.Close()
$dtbatch.Clear()
$bulkcopy.Dispose()
$dtbatch.Dispose()
# return whatever you want, or don't.
return $error[0]
}
# BLOCK 3: Create runspace and add to runspace pool
if ($datatable.rows.count -eq 50000) {
$runspace = [PowerShell]::Create()
$null = $runspace.AddScript($scriptblock)
$null = $runspace.AddArgument($connstring)
$null = $runspace.AddArgument($datatable)
$null = $runspace.AddArgument($batchsize)
$runspace.RunspacePool = $pool
# BLOCK 4: Add runspace to runspaces collection and "start" it
# Asynchronously runs the commands of the PowerShell object pipeline
$runspaces += [PSCustomObject]@{ Pipe = $runspace; Status = $runspace.BeginInvoke() }
$datatable.Clear()
}
# BLOCK 5: Wait for runspaces to finish
while ($runspaces.Status.IsCompleted -notcontains $true) {}
# BLOCK 6: Clean up
foreach ($runspace in $runspaces ) {
# EndInvoke method retrieves the results of the asynchronous call
$results = $runspace.Pipe.EndInvoke($runspace.Status)
$runspace.Pipe.Dispose()
}
$pool.Close()
$pool.Dispose()
# Bonus block 7
# Look at $results to see any errors or whatever was returned from the runspaces
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.