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

如何为PowerShell管道设置Throttle Limit以调优并行请求数

调整PowerShell域内计算机查询的并发请求数(Throttle Limit)

你当前的代码其实是串行执行的——Select-Object会逐个遍历每台计算机,每次只发起一个Get-WmiObject请求,并没有实现并行。要实现并行查询并控制同时发起的请求数量,需要改用支持并行执行的命令,并通过ThrottleLimit参数调整并发数,以下分两种PowerShell版本给出方案:

方案1:PowerShell 7及以上版本(推荐)

使用ForEach-Object -Parallel,这个命令原生支持并行处理,且可以通过ThrottleLimit直接设置并发上限(默认值为5)。

示例代码:

# 获取域内所有计算机及描述属性
$comps = Get-ADComputer * -Properties description

# 并行处理,设置并发数为10(可根据实际情况调整)
$results = $comps | ForEach-Object -Parallel {
    $computerName = $_.Name
    try {
        $wmiObj = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $computerName -ErrorAction Stop
        $user = $wmiObj.Username
    } catch {
        $user = "无法连接/查询失败"
    }
    [PSCustomObject]@{
        Name        = $computerName
        User        = $user
        Description = $_.description
    }
} -ThrottleLimit 10

# 输出结果到GridView
$results | Out-GridView

方案2:PowerShell 5.x版本

如果用的是PowerShell 5.x,可使用Invoke-Command实现并行,它的ThrottleLimit参数默认值为32,同样可以自定义调整。

示例代码:

# 获取域内所有计算机及描述属性
$comps = Get-ADComputer * -Properties description
$computerNames = $comps.Name

# 并行查询,设置并发数为15(可根据实际情况调整)
$results = Invoke-Command -ComputerName $computerNames -ThrottleLimit 15 -ScriptBlock {
    try {
        $wmiObj = Get-WmiObject -Class Win32_ComputerSystem -ErrorAction Stop
        $user = $wmiObj.Username
    } catch {
        $user = "无法连接/查询失败"
    }
    [PSCustomObject]@{
        Name        = $env:COMPUTERNAME
        User        = $user
        Description = ($using:comps | Where-Object Name -eq $env:COMPUTERNAME).description
    }
}

# 清理远程会话并输出结果
Remove-PSSession -Session $results.PSComputerName
$results | Select-Object Name, User, Description | Out-GridView

关于ThrottleLimit的设置建议

  • 不要设置过大:并发数过高可能会导致域控制器或网络过载,引发查询超时、失败等问题。
  • 建议从10-20开始测试,根据实际的网络带宽、域控制器负载调整到合适的数值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 08:05:37