如何修改PowerShell脚本批量更新Intune匹配CSV序列号的设备分类
解决Intune设备按CSV序列号匹配更新分类的PowerShell脚本问题
核心需求
遍历所有Intune管理设备,匹配CSV文件中的序列号,将同时存在于两者的设备分类更新为指定的「in use」分类(已知分类ID)。
原脚本问题分析
原脚本仅针对单个硬编码的序列号做匹配,未实现CSV批量读取与高效匹配逻辑,嵌套循环无效果通常是因为匹配逻辑错误或未正确加载CSV数据。
修改后的完整脚本
# 连接MS Graph并切换到beta版本 Connect-MSGraph Update-MSGraphEnvironment -SchemaVersion 'beta' # 定义更新设备分类的函数 function Set-DeviceCategory { param( [Parameter(Mandatory)] [string]$DeviceID, [Parameter(Mandatory)] [string]$DeviceCategoryID ) $body = @{ '@odata.id' = "https://graph.microsoft.com/beta/deviceManagement/deviceCategories/$DeviceCategoryID" } try { Invoke-MSGraphRequest -HttpMethod PUT -Url "deviceManagement/managedDevices/$DeviceID/deviceCategory/`$ref" -Content $body return $true } catch { Write-Warning "更新设备ID $DeviceID 时出错: $_" return $false } } # 1. 读取CSV文件(替换为你的CSV路径,确保CSV包含SerialNumber列) $csvPath = "C:\path\to\your\serialnumbers.csv" $csvSerials = @{} Import-Csv -Path $csvPath | ForEach-Object { # 转换为大写避免大小写匹配问题,可根据实际情况调整 $csvSerials[$_.SerialNumber.ToUpper()] = $true } # 2. 获取所有Intune管理设备 try { $intuneDevices = (Invoke-MSGraphRequest -HttpMethod GET -Url 'deviceManagement/managedDevices').value Write-Host "成功获取到 $($intuneDevices.Count) 台Intune设备" } catch { Write-Error "获取Intune设备失败: $_" exit 1 } # 3. 遍历设备并匹配更新 $successCount = 0 $failCount = 0 $notFoundCount = 0 $intuneDevices | ForEach-Object { $deviceSerial = $_.serialnumber.ToUpper() if ($csvSerials.ContainsKey($deviceSerial)) { # 替换为你的「in use」分类ID $targetCategoryID = "your-category-id-here" Write-Host "正在更新序列号 $deviceSerial 的设备分类..." if (Set-DeviceCategory -DeviceID $_.id -DeviceCategoryID $targetCategoryID) { $successCount++ Write-Host "序列号 $deviceSerial 更新成功" } else { $failCount++ } } else { $notFoundCount++ } } # 输出统计结果 Write-Host "`n=== 更新完成 ===" Write-Host "成功更新: $successCount 台" Write-Host "更新失败: $failCount 台" Write-Host "CSV中未匹配到的设备: $notFoundCount 台"
关键优化点
- 高效匹配:使用哈希表存储CSV序列号,将O(n)的嵌套循环匹配优化为O(1)的查找,大幅提升处理效率
- 错误处理:为API调用添加try/catch块,捕获并输出错误信息,便于排查问题
- 大小写兼容:将序列号统一转换为大写(或小写),避免因大小写不一致导致的匹配失败
- 统计输出:添加更新结果统计,清晰展示处理情况
注意事项
- 确保CSV文件包含名为
SerialNumber的列(可根据实际列名修改脚本中的$_.SerialNumber) - 替换脚本中的
$csvPath为你的CSV文件实际路径 - 替换
$targetCategoryID为预先创建的「in use」分类的ID - 运行脚本的账号需具备
DeviceManagementManagedDevices.ReadWrite.All权限 - 若设备数量较多,可考虑添加分页逻辑(Intune API默认返回100条设备,超过时需处理
@odata.nextLink)
内容的提问来源于stack exchange,提问作者PowerShellWiz
相关产品推荐
相关产品推荐

