0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

WindowsServer2012でforeach-object -parallel をやりたい

Posted at

それらしいものを

function Start-ThrottlingJob {
    Param(
        [int]$StartupInterval = 2,
        [int]$IntervalSecond = 5,
        [int]$Parallel = 5,
        [string]$Name,
        [Parameter(ValueFromPipeline=$True)][object[]]$ArgumentList,
        [Parameter(Mandatory=$True)][scriptblock]$ScriptBlock
    )
    begin {
        $q = New-Object System.Collections.Queue
    }
    process {
        foreach($o in $ArgumentList){
            $q.Enqueue($o) | Out-Null
        }
    }
    end {
        while($q.Count -ne 0)
        {
            if ((get-job -state Running).Count -ge $Parallel) { break }
            $task = $q.dequeue()
            $n = if ($Name -ne $null) { $task.$name } elseif ($task -is [string]) { $task }
            Start-Job $ScriptBlock -Name $n -ArgumentList $task -Verbose
            Start-Sleep $StartupInterval
        }
        while($q.Count -ne 0)
        {
            Start-Sleep $IntervalSecond
            if ((get-job -state Running).Count -ge $Parallel) { continue }
            $task = $q.dequeue()
            $n = if ($Name -ne $null) { $task.$name } elseif ($task -is [string]) { $task }
            Start-Job $ScriptBlock -Name $n -ArgumentList $task
        }
    }
}

テスト

$sb = { param($a) sleep (get-random -min 1 -max 60); echo $a.FullName }
ls | Start-ThrottlingJob -StartupInterval 1 -Parallel 10 -name name -ScriptBlock $sb

ゴテゴテしてしまったけど、それらしく動いたので良いことにする

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?