簡體   English   中英

不使用運行空間池來管理Powershell運行空間的正確方法是什么?

[英]What is the right way to manage powershell runspace without using runspace pool?

我需要按一定順序在遠程Powershell會話中執行一些cmdlet:例如。 如果此通訊組存在,則將該用戶添加到組中,但我不斷遇到有關運行空間狀態的錯誤,或者我創建了太多運行空間,因此我必須等待一段時間。 我不能使用運行空間池,因為對於每個會話,在執行其他cmdlet之前,我都需要獲取cmdlet的結果。

我試圖在同一運行空間中執行cmdlet塊腳本(取決於其他結果的兩個或三個chdlet),但是由於運行空間未打開,我得到了無效的運行空間狀態。 在完成cmdlet塊腳本之后,我確實處理了運行空間,我也確實處理了powershell會話。

在該站點上搜索了一些答案之后,我閱讀了某人在一個相關問題中的答案,他說在每次調用后都將運行空間和powershell會話soud丟棄並重新創建,但是不久之后我收到一條錯誤消息,說我無法創建更多內容運行空間。

    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);
    }

我應該如何正確管理運行空間,以便確保正確執行每個cmdlet塊腳本?

非常感謝你!!!

我發現克里斯西·勒梅爾(Chrissy LeMaire)盡可能簡化了此模板“ 簡化的運行空間” ,您所要做的就是傳遞腳本塊

下面是模板

# 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM