2

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?

0

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.