scorpion35
scorpion35

Reputation: 1084

pwsh - get only values in ConvertTo-Json

Pwsh version: 7.4.5

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

Produces this result

WARNING: Resulting JSON is truncated as serialization has exceeded the set depth of 2.
[
  {
    "IPv4Address": [
      "MSFT_NetIPAddress (Name = \";:8A?8;A8??55;?55;55;\", CreationClassName = \"\", SystemCreationClassName = \"\", SystemName = \"\")"
    ]
  },
  {
    "IPv4Address": [
      "MSFT_NetIPAddress (Name = \";@C8???8???8;?;55;?55;55;\", CreationClassName = \"\", SystemCreationClassName = \"\", SystemName = \"\")"
    ]
  },
  ...
]

And if I try

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

this produces even bigger (like full) json object.

I understand each IPv4Address is it's own object, but I am looking to get only the IP address of these objects. Does anyone know if there's a way to just get the values on IPv4Address ?

Something like

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

TIA

Upvotes: 1

Views: 56

Answers (2)

ninMonkey
ninMonkey

Reputation: 7501

You can put a helper function in your script, or profile. Then you can re-use it easier. It's essentially Santi's answer.

filter Flatten.IPAddr { 
  # helper function that flattens NetIPConfig for exporting to json/csv
  [pscustomobject]@{ 
     IPv4Address  = $_.IPv4Address.IPAddress 
     ComputerName = $_.ComputerName
  }
}

tips:

$list | Flatten.IPAddr  | ConvertTo-Json 

shows serialized output as json

Upvotes: 0

Santiago Squarzon
Santiago Squarzon

Reputation: 60838

The actual IP Address as string is nested in the .IPv4Address.IPAddress property so you can use a calculated property with Select-Object to get it:

Get-NetIPConfiguration -Detailed |
    Select-Object @{ N = 'IPv4Address'; E = { $_.IPv4Address.IPAddress }} |
    ConvertTo-Json

Upvotes: 2

Related Questions