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

求批量识别IoT设备类型的PowerShell脚本实现示例

PowerShell IoT设备类型识别实现示例

适配提示:PowerShell环境默认自带的curl为Invoke-WebRequest命令别名,和原生curl语法不通用,以下示例采用PowerShell原生语法实现,兼容Windows PowerShell 5.1及PowerShell 7+版本:

  • Test-Connection对应shell/batch中的ping命令
  • Invoke-WebRequest对应shell/batch中的curl/wget命令

完整基础脚本示例

# 配置项,请根据实际场景修改
$hostListPath = "C:\path\to\hosts.txt" # 主机名列表路径,每行存储一个主机名
$outputPath = "C:\path\to\device_result.csv" # 识别结果输出路径
$deviceInfoApi = "/api/device/info" # 设备标识信息拉取接口路径
$timeoutSec = 3 # 网络请求超时时间,单位秒

# 初始化输出文件写入表头
"hostname,device_type" | Out-File -FilePath $outputPath -Encoding utf8

# 读取主机列表,自动跳过空行
$hostList = Get-Content -Path $hostListPath | Where-Object { $_.Trim() -ne "" }

foreach ($hostname in $hostList) {
    # 第一步:检测主机是否存活(ICMP检测,发1个包,超时1秒)
    $alive = Test-Connection -ComputerName $hostname -Count 1 -TimeoutSeconds 1 -Quiet -ErrorAction SilentlyContinue
    if (-not $alive) {
        "$hostname,NOT RESPONDING" | Out-File -FilePath $outputPath -Encoding utf8 -Append
        continue
    }

    # 第二步:拉取设备标识信息判定类型
    try {
        $response = Invoke-WebRequest -Uri "http://$hostname$deviceInfoApi" -TimeoutSec $timeoutSec -UseBasicParsing -ErrorAction Stop
        # 若接口返回非JSON格式,可直接用字符串匹配规则替换下面的JSON解析逻辑
        $deviceInfo = $response.Content | ConvertFrom-Json
        # 类型判定规则,请根据实际返回字段修改
        if ($deviceInfo.battery_type -eq "lithium") {
            $deviceType = "A"
        } elseif ($deviceInfo.battery_type -eq "alkaline") {
            $deviceType = "B"
        } else {
            $deviceType = "UNKNOWN"
        }
        "$hostname,$deviceType" | Out-File -FilePath $outputPath -Encoding utf8 -Append
    } catch {
        # 接口请求失败统一判定为无响应
        "$hostname,NOT RESPONDING" | Out-File -FilePath $outputPath -Encoding utf8 -Append
    }
}

批量场景优化说明(针对2万台设备量级)

单线程执行上述脚本处理两万台设备耗时较长,可根据PowerShell版本选择并发方案提升效率:

  • 若使用PowerShell 7+版本,可将foreach循环替换为ForEach-Object -Parallel开启并发处理,示例写法:
$hostList | ForEach-Object -Parallel {
    $hostname = $_
    # 并行作用域调用外部变量需要加$using:前缀
    $outputPath = $using:outputPath
    $deviceInfoApi = $using:deviceInfoApi
    $timeoutSec = $using:timeoutSec
    # 剩余逻辑和上述foreach循环内的检测逻辑完全一致
} -ThrottleLimit 50 # 并发数可根据网络环境调整,建议设置为30-100
  • 若需兼容Windows PowerShell 5.1,可使用Start-Job实现多任务并发。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 00:36:04