pwsh 使用 RunspacePool 进行并发操作

# 创建运行空间池
$runspacePool = [RunspaceFactory]::CreateRunspacePool(1, 100)  # 创建运行空间池 最大 100 个
$runspacePool.Open()

$fakeIdDcit = @{}
$fakeIdDcit["9D370B71F76FC2"] = 1
$fakeIdDcit["21061FHHR00CBN"] = 2
$fakeIdDcit["23261FDF600326"] = 3
$fakeIdDcit["FC9711A26A9E1B"] = 4
$fakeIdDcit["1B251FDF6007SK"] = 5
$fakeIdDcit["4C7976D4FC7DC4"] = 6

$arry = 200..255

# 定义任务
$tasks = @()
$arry | ForEach-Object {

    $powershell = [PowerShell]::Create()
    $powershell.RunspacePool = $runspacePool
    $cmdScript = $powershell.AddScript({
            param ($ipPart, $fakeIdDcit)
            # Start-Sleep -Seconds 2  # 模拟耗时操作
            # Write-Host "任务 $taskName 完成!"

            Set-Location C:\Users\xu\adb\

            $ip = "192.168.31.$($ipPart)"

            $result = Test-Connection $ip -Count 1 -Quiet; # ping 地址     
            # echo $ip, $result
            if (-not $result) {
                return 
            }

            $result = Test-NetConnection $ip -Port 6667 -InformationLevel Quiet
            if (-not $result) {
                return 
            }

            $addr = "$($ip):6667"
            .\adb.exe connect $addr  | Out-Null
            if ($?) {

                $id = .\adb.exe -s $addr shell "getprop ro.serialno"
                $mac = .\adb.exe -s $addr  shell "ip addr show eth0 " | Select-String '(?<=link/ether)\s[\w\:]+' | % Matches | % Value `                

                $idx = $fakeIdDcit[$id]

                Write-Output "$idx, $mac, $id, $ip"

                .\adb.exe disconnect $addr | Out-Null
            }

        })

    $cmdScript.AddArgument($_) | Out-Null
    $cmdScript.AddArgument($fakeIdDcit) | Out-Null

    $tasks += [PSCustomObject]@{ PowerShell = $powershell; AsyncResult = $powershell.BeginInvoke() }
}

# 等待所有任务完成
$tasks | ForEach-Object {
    $_.PowerShell.EndInvoke($_.AsyncResult)
    $_.PowerShell.Dispose()
}

# 关闭运行空间池
$runspacePool.Close()
$runspacePool.Dispose()

Write-Output ""
Write-Host "所有任务完成" -ForegroundColor Gray
上一篇
下一篇