将PowerShell对象转换为JSON,特别是IP地址

时间:2017-09-14 19:07:41

标签: json powershell networking ipv4

需要获取有关网络接口的一些信息:

> Get-NetIPConfiguration | select IPv4Address, InterfaceAlias, InterfaceDes    cription | ConvertTo-Json

回应

[
    {
        "IPv4Address":  [
                            "MSFT_NetIPAddress (Name = \";C?8;@B8CC8;??55;:55;55;\", CreationClassName = \"\", SystemCr
eationClassName = \"\", SystemName = \"\")"
                        ],
        "InterfaceAlias":  "wifi",
        "InterfaceDescription":  "Qualcomm Atheros AR5BWB222 Wireless Network Adapter"
    },
    {
        "IPv4Address":  [
                            "MSFT_NetIPAddress (Name = \";@C8???8;??8??B55;@55;55;\", CreationClassName = \"\", SystemC
reationClassName = \"\", SystemName = \"\")"
                        ],
        "InterfaceAlias":  "Ethernet",
        "InterfaceDescription":  "Realtek PCIe GBE Family Controller"
    }
]

这看起来很奇怪。我希望有类似的东西:

[
    {
        "IPv4Address": "12.3.3.4",
        "InterfaceAlias":  "wifi",
        "InterfaceDescription":  "Qualcomm Atheros AR5BWB222 Wireless Network Adapter"
        "NetAdapter.Status" : "connected"
    },
    {
        "IPv4Address":  "192.168.0.1",
        "InterfaceAlias":  "Ethernet",
        "InterfaceDescription":  "Realtek PCIe GBE Family Controller"
        "NetAdapter.Status" : "connected"
    }
]

还需要连接或断开接口状态,它存储在NetAdapter.Status中。 请帮忙。最好把它全部写成一行。

2 个答案:

答案 0 :(得分:2)

您需要更深入地遍历对象:

Get-NetIPConfiguration | select IPv4Address, InterfaceAlias, InterfaceDescription | 
  ConvertTo-Json -Depth 5

默认情况下,powershell只有3级深度

答案 1 :(得分:0)

不在一行......

$n = Get-NetIPConfiguration | select InterfaceIndex, IPv4Address, InterfaceAlias, InterfaceDescription, NetAdapter
ForEach( $a in $n ){
    $a.Ipv4Address =  $a.Ipv4Address.IpAddress
    $a | Add-Member -type NoteProperty -name Status -value $a.NetAdapter.Status
    $a.PSObject.Properties.Remove('NetAdapter')
}

$n
$n | ConvertTo-Json

结果:

InterfaceIndex       : 10
IPv4Address          : 192.168.99.135
InterfaceAlias       : wifi
InterfaceDescription : Qualcomm Atheros AR5BWB222 Wireless Network Adapter
Status               : Up

InterfaceIndex       : 16
IPv4Address          : 169.254.153.248
InterfaceAlias       : Ethernet
InterfaceDescription : Realtek PCIe GBE Family Controller
Status               : Disconnected

[
    {
        "InterfaceIndex":  10,
        "IPv4Address":  "192.168.99.135",
        "InterfaceAlias":  "wifi",
        "InterfaceDescription":  "Qualcomm Atheros AR5BWB222 Wireless Network Adapter",
        "Status":  "Up"
    },
    {
        "InterfaceIndex":  16,
        "IPv4Address":  "169.254.153.248",
        "InterfaceAlias":  "Ethernet",
        "InterfaceDescription":  "Realtek PCIe GBE Family Controller",
        "Status":  "Disconnected"
    }
]

我相信,有更多短路,可能是最佳方式