How does threading in powershell work?

前端 未结 6 1443
有刺的猬
有刺的猬 2020-12-23 23:14

I want to parallelize some file-parsing actions with network activity in powershell. Quick google for it, start-thread looked like a solution, but:

T

6条回答
  •  [愿得一人]
    2020-12-23 23:21

    The thing that comes closest to threads and is way more performant than jobs is PowerShell runspaces.

    Here is a very basic example:

    # the number of threads
    $count = 10
    
    # the pool will manage the parallel execution
    $pool = [RunspaceFactory]::CreateRunspacePool(1, $count)
    
    try {    
        $pool.Open()
    
        # create and run the jobs to be run in parallel
        $jobs = New-Object object[] $count
        for ($i = 0; $i -lt $count; $i++) {
            $ps = [PowerShell]::Create()
            $ps.RunspacePool = $pool
    
            # add the script block to run
            [void]$ps.AddScript({
                param($Index)
                Write-Output "Index: $index"
            })
    
            # optional: add parameters
            [void]$ps.AddParameter("Index", $i)
    
            # start async execution
            $jobs[$i] = [PSCustomObject]@{
                PowerShell = $ps
                AsyncResult = $ps.BeginInvoke()
            }
        }
        foreach ($job in $jobs) {
            try {
                # wait for completion
                [void]$job.AsyncResult.AsyncWaitHandle.WaitOne()
    
                # get results
                $job.PowerShell.EndInvoke($job.AsyncResult)
            }
            finally {
                $job.PowerShell.Dispose()
            }
        }
    }
    finally {
        $pool.Dispose()
    }
    

    Beyond that, you can do more advanced things like throttle the number of parallel runspaces on the pool, or import functions and variables from the current session etc.

提交回复
热议问题