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

如何在PowerShell Web请求响应中获取deviceName字段值

解决PowerShell中获取Web请求响应JSON字段的问题

你遇到的问题是因为Invoke-WebRequest返回的$Result并非直接的JSON对象,而是包含响应元数据的HtmlWebResponseObject实例,JSON内容实际存储在它的Content属性中。直接用$Result['data'][0]['deviceName']访问的是响应对象的属性,而非JSON结构里的字段,所以无法得到结果。

解决步骤:

  1. 提取响应中的JSON字符串内容,转换为PowerShell可操作的对象
  2. 从转换后的对象中读取目标字段

具体实现代码:

分步处理(可读性更好):

# 发起Web请求
$Result = Invoke-WebRequest -Uri $RequestUrl -Method $apiMethod -Body $token -ErrorAction:Stop -UseBasicParsing
# 将响应内容转换为JSON对象
$jsonResponse = $Result.Content | ConvertFrom-Json
# 获取deviceName的值
$deviceName = $jsonResponse.data[0].deviceName

一行式简化:

$deviceName = (Invoke-WebRequest -Uri $RequestUrl -Method $apiMethod -Body $token -ErrorAction:Stop -UseBasicParsing).Content | ConvertFrom-Json | ForEach-Object { $_.data[0].deviceName }

验证方法:

你可以先输出转换后的对象结构,确认字段是否正确:

$jsonResponse | Format-List

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 09:57:21