Steve
Steve

Reputation: 228

Can I select a property and a sub-property in a Powershell one-liner

I am trying to get a JSON array of MAC addresses and associated IP addresses of DHCP leases from a Windows DHCP server using PowerShell.

Using this: Get-DhcpServerv4Lease -ScopeId 192.168.0.0 | Where-Object {$_.AddressState -eq "ActiveReservation"} | Select-Object -Property ClientId,IPAddress | ConvertTo-Json

I get this output:

[
  {
    "ClientId": "00-11-22-33-44-55",
    "IPAddress": {
      "Address": 12345678,
      "AddressFamily": 2,
      "ScopeId" : null,
      "IPAddressToString": "192.168.0.2"
    }
  },
  {
    "ClientId": "00-11-22-33-44-66",
    "IPAddress": {
      "Address": 12345679,
      "AddressFamily": 2,
      "ScopeId" : null,
      "IPAddressToString": "192.168.0.3"
    }
  }
]

But I only want the ClientId and value of IPAddressToString, not the other properties:

[
  {
    "ClientId": "00-11-22-33-44-55",
    "IPAddressToString": "192.168.0.2"
  },
  {
    "ClientId": "00-11-22-33-44-66",
    "IPAddressToString": "192.168.0.3"
  }
]

Is this possible in a one-liner?

Upvotes: 2

Views: 364

Answers (2)

Theo
Theo

Reputation: 61068

Since this returned json is an array, I think you need to loop through the elements like

Get-DhcpServerv4Lease -ScopeId 192.168.0.0 | 
    Where-Object {$_.AddressState -eq "ActiveReservation"} | 
    ForEach-Object {
        $_ | Select-Object ClientId, @{Name = 'IPAddress'; Expression = {$_.IPAddress.IPAddressToString}}
    } | ConvertTo-Json

Output:

[
    {
        "ClientId":  "00-11-22-33-44-55",
        "IPAddress":  "192.168.0.2"
    },
    {
        "ClientId":  "00-11-22-33-44-66",
        "IPAddress":  "192.168.0.3"
    }
]

P.S. You can write this as a one-liner, but that would make the code harder to read, easier to make mistakes and there is nothing to be gained by writing LONG lines of code. You'll make things only more difficult for yourself by doing that

Upvotes: 0

Peter the Automator
Peter the Automator

Reputation: 918

Try this

Get-DhcpServerv4Lease -ScopeId 192.168.0.0 | Where-Object { $_.AddressState -eq "ActiveReservation" } |  Select-Object -Property ClientId, @{Name = "Address"; Expression = { $_.IpAddress.IPAddressToString} } | ConvertTo-Json

Upvotes: 2

Related Questions