並列処理にはいろいろは方法があるみたいだが、一番簡単そうな Start-Job を使ったサンプル
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 |
Function Get-Example1 { Write-Verbose -Verbose "This is an example1" Start-Sleep -Milliseconds 600 $A = Get-Date Write-Host "This is an example2" $A.ToString() } Function Get-Example2 { Write-Verbose -Verbose "This is an example2" Start-Sleep -Milliseconds 300 $A = Get-Date Write-Host "This is an example2" $A.ToString() } $block = (Get-Command Get-Example1).ScriptBlock Start-Job -ScriptBlock $block -name "Get-Example1" $block = (Get-Command Get-Example2).ScriptBlock Start-Job -ScriptBlock $block -name "Get-Example2" do{ # ジョブ取得 $Jobs = Get-Job [Boolean]$IsRunning = $false foreach( $Job in $Jobs ) { if ( $Job.State -eq "Running") { $IsRunning = $true } } if ( $Jobs -ne $null ) { $Now = Get-Date $Message = "未処理ジョブ " + $Now write-host $Message $AllJobs | Format-Table -Property Id, Name, State, Location -AutoSize | Out-Host write-host "" write-host "" write-host "" sleep 1 } } while ( $IsRunning -eq $true ) #各状態毎の結果確認を取得 # 正常終了したジョブ $CompletedJobs = $Jobs | ? { $_.State -eq "Completed" } # 異常終了したジョブ $FailedJobs = Get-Job | ? { $_.State -eq "Failed" } # 切断されたジョブ(ジョブ強制削除) $DisconnectedJobs = Get-Job | ? { $_.State -eq "Disconnected" } if ( $CompletedJobs -ne $null ) { foreach ( $Job in $CompletedJobs ) { $Location = $Job.Location # 戻り値取得 # $CompletedJob = Receive-Job -Id $Job.Id $Job.Name write-host "[INFO]" $Location $Job.Name $Job.Id "Completed" # Job 削除 Remove-Job -Id $Job.Id } } if ( $FailedJobs -ne $null ) { # 一覧表示 write-host "Fail Job" $FailedJobs | Format-Table -Property Id, Name, State, Location -AutoSize | Out-Host write-host "" # 異常終了した Job を処理 foreach ( $Job in $FailedJobs ) { $Location = $Job.Location # 標準出力と戻り値を echo して Job 削除 write-host "[FAIL] $Location Failed" write-host "[FAIL] ------------ $Location stdout echo Start ------------" $Failechos = Receive-Job -Id $Job.Id if ( $Failechos -ne $null ) { foreach ( $Failecho in $Failechos ) { write-host $Failecho } } write-host "[FAIL] ------------ $Location stdout echo End ------------" Remove-Job -Id $Job.Id } } if ( $DisconnectedJobs -ne $null ) { # 一覧表示 write-host "Disconnect Job" $DisconnectedJobs | Format-Table -Property Id, Name, State, Location -AutoSize | Out-Host write-host "" # Job 強制削除 foreach ( $Job in $DisconnectedJobs ) { Stop-Job -Id $Job.Id Remove-Job -Id $Job.Id } } |
コメント