PowerShell获取Intune戴尔设备序列号:跳过JSON开头元数据方法
解决Get-IntuneManagedDevice返回JSON含元数据无法提取序列号的问题
你的问题出在Get-IntuneManagedDevice返回的结果自带OData元数据(@odata.context、@odata.count等字段),实际设备数据嵌套在value数组里,原代码直接遍历顶层对象自然拿不到serialNumber。下面是两种自动化处理方案:
方案一:直接管道处理(无需生成JSON文件)
跳过文件存储步骤,直接在管道中提取设备数组并输出序列号,效率更高:
Get-IntuneManagedDevice -Filter "manufacturer eq 'Dell Inc.'" -Top 100 | Select-Object -ExpandProperty value | ForEach-Object { Write-Output $_.serialNumber }
Select-Object -ExpandProperty value会直接把嵌套的设备数组展开,后续遍历就能直接访问每个设备的serialNumber属性。
方案二:保留JSON文件的处理方式
如果需要保留JSON文件作为记录,读取后先定位到value数组再遍历:
# 生成带元数据的JSON文件 Get-IntuneManagedDevice -Filter "manufacturer eq 'Dell Inc.'" -Top 100 | ConvertTo-Json -Depth 3 | Out-File -FilePath ".\dellTags.json" # 读取并处理JSON $test = Get-Content -Path .\dellTags.json | ConvertFrom-Json $test.value | ForEach-Object { Write-Output $_.serialNumber }
这里通过$test.value直接获取设备对象数组,再遍历提取序列号即可。
额外补充:处理分页获取所有戴尔设备
如果戴尔设备数量超过100台,原代码的-Top 100只能拿到第一页数据,需要处理@odata.nextLink实现分页获取:
$allDellDevices = @() $nextLink = $null do { if ($nextLink) { # 分页请求下一页数据 $devices = Invoke-RestMethod -Uri $nextLink -Headers (Get-MSGraphAuthenticationHeader) } else { # 初始请求第一页 $devices = Get-IntuneManagedDevice -Filter "manufacturer eq 'Dell Inc.'" -Top 100 } $allDellDevices += $devices.value $nextLink = $devices.'@odata.nextLink' } while ($nextLink) # 输出所有序列号 $allDellDevices | ForEach-Object { Write-Output $_.serialNumber }
注意:使用Invoke-RestMethod前需确保已通过Connect-MSGraph完成Intune认证,Get-MSGraphAuthenticationHeader用于获取认证头(部分模块可能需要调整为对应的认证方式)。
内容的提问来源于stack exchange,提问作者ITatMC
相关产品推荐
相关产品推荐

