Search code examples
powershelldhcp

How to query Windows DHCP server across multiple scopes for a hostname in Powershell


I am trying to write a one liner that allows me to specify a hostname and then search across a list of scopeIDs for that DHCP lease. Powershell version:

Major  Minor  Build  Revision
-----  -----  -----  --------
5      1      14393  576

So far, I am using this:

Get-DhcpServerv4Lease -ComputerName Server -ScopeId 172.17.16.0 | Where-Object HostName -match Hostname | FT ipaddress,hostname,clientid,addressstate
Get-DhcpServerv4Lease -ComputerName Server -ScopeId 172.17.17.0 | Where-Object HostName -match Hostname | FT ipaddress,hostname,clientid,addressstate
Get-DhcpServerv4Lease -ComputerName Server -ScopeId 172.17.18.0 | Where-Object HostName -match Hostname | FT ipaddress,hostname,clientid,addressstate
Get-DhcpServerv4Lease -ComputerName Server -ScopeId 172.17.19.0 | Where-Object HostName -match Hostname | FT ipaddress,hostname,clientid,addressstate
Get-DhcpServerv4Lease -ComputerName Server -ScopeId 172.17.76.0 | Where-Object HostName -match Hostname | FT ipaddress,hostname,clientid,addressstate 

This works, but I have to change the hostname on each line using find/replace.

I was thinking of something like,

Get-DhcpServerv4Lease -ComputerName Server -ScopeId 172.17.16.0,172.17.17.0,172.17.18.0,172.17.19.0,172.17.76.0 | Where-Object HostName -match Hostname | FT ipaddress,hostname,clientid,addressstate

but the array doesn't work under the ScopeId. Any help would be appreciated.


Solution

  • You could pipe in the IP addresses with a foreach or the alias % :

    "172.17.16.0","172.17.17.0","172.17.18.0","172.17.19.0","172.17.76.0" | % {
        Get-DhcpServerv4Lease -ComputerName Server -ScopeId $_ |
        Where-Object HostName -match Hostname |
        FT ipaddress,hostname,clientid,addressstate
    }