You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell 7中如何在Start-ThreadJob内递增全局变量test_con?

PowerShell 7中用Start-ThreadJob统计Ping通计算机数量的解决方法

你的代码无法正确递增$test_con的核心原因是:每个Start-ThreadJob创建的线程拥有独立的作用域,脚本块内的$test_con要么是线程局部变量,要么直接修改全局变量会触发多线程竞态条件(多个线程同时读写导致计数错误)。以下是两种可靠的实现方式:

方法一:收集Job输出统计(推荐)

让每个线程Job返回Ping检测的布尔结果,待所有Job完成后统一统计成功数量,完全避免变量共享问题:

# 示例计算机列表
$computers = @("127.0.0.1", "google.com", "invalid-host")

# 启动所有线程Job并保存Job对象
$jobs = foreach ($computer in $computers) {
    Start-ThreadJob -ThrottleLimit 100 -ScriptBlock {
        Test-Connection $using:computer -Count 1 -TimeoutSeconds 2 -Quiet
    }
}

# 等待所有Job完成并获取结果(自动移除Job)
$results = $jobs | Receive-Job -Wait -AutoRemoveJob

# 统计成功Ping通的数量
$test_con = ($results | Where-Object { $_ }).Count

Write-Host "成功Ping通的计算机数量:$test_con"

方法二:使用线程安全计数器

如果需要在线程内直接更新计数,必须用线程安全的原子操作避免竞态条件,借助[System.Threading.Interlocked]类实现:

# 初始化线程安全计数器
$test_con = 0
$counter = [ref]$test_con

# 示例计算机列表
$computers = @("127.0.0.1", "google.com", "invalid-host")

foreach ($computer in $computers) {
    Start-ThreadJob -ThrottleLimit 100 -ScriptBlock {
        if (Test-Connection $using:computer -Count 1 -TimeoutSeconds 2 -Quiet) {
            # 原子性递增计数器,确保多线程下计数准确
            [System.Threading.Interlocked]::Increment($using:counter)
        }
    }
}

# 等待所有Job完成并清理
Get-Job | Wait-Job | Remove-Job

Write-Host "成功Ping通的计算机数量:$test_con"

内容的提问来源于stack exchange,提问作者Tazounet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 03:55:14