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

如何在PowerShell中仅提取IPv4地址值并转为JSON格式

提取IPv4地址并生成指定格式JSON的PowerShell实现方法

环境:Pwsh版本 7.4.5

问题背景

执行以下命令时会出现JSON截断警告,且无法获取到实际IP地址值:

Get-NetIPConfiguration -Detailed | Select-Object -Property IPv4Address | ConvertTo-Json

而使用-ExpandProperty展开后会生成包含大量冗余信息的完整JSON对象,不符合需求。我们需要仅提取每个IPv4Address对象中的IP地址值,生成如下格式的JSON:

[
  {"IPv4Address": "1.2.3.4"},
  {"IPv4Address": "11.21.31.41"},
  {"IPv4Address": "12.22.32.42"},
  {"IPv4Address": "13.23.33.43"}
]

实现命令

Get-NetIPConfiguration -Detailed | 
  Select-Object -ExpandProperty IPv4Address | 
  Where-Object { $_.IPAddress } |
  Select-Object @{Name='IPv4Address'; Expression={ $_.IPAddress }} |
  ConvertTo-Json

命令说明

  • Select-Object -ExpandProperty IPv4Address:直接展开IPv4Address属性,获取到每个独立的MSFT_NetIPAddress对象,而非嵌套的数组结构
  • Where-Object { $_.IPAddress }:过滤掉没有有效IP地址的条目,避免生成空值的JSON项
  • Select-Object @{Name='IPv4Address'; Expression={ $_.IPAddress }}:自定义输出属性,仅保留对象中的IPAddress字段值,并将属性名设为IPv4Address,匹配目标格式
  • ConvertTo-Json:将处理后的对象集合转换为JSON格式,由于仅处理了单层属性,不会出现深度截断问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 20:22:03