如何在 Powershell 中跨多个范围查询 Windows DHCP 服务器以获取主机名

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

我正在尝试编写一个单行程序,它允许我指定一个主机名,然后在一个 scopeID 列表中搜索该 DHCP 租约。 Powershell 版本:

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

到目前为止,我正在使用这个:

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 

这可行,但我必须使用 find/replace 更改每一行的主机名。

我在想,

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

但该数组在 ScopeId 下不起作用。任何帮助将不胜感激。

您可以使用 foreach 或别名 % :

输入 IP 地址
"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
}

以下内容并不完全是单行的,但适用于范围比实际手动识别多得多的任何人:

$allscope = Get-DhcpServerv4Scope -ComputerName "dhcpserver"

foreach ($ScopeID in $allscope) 
{Get-DhcpServerv4Lease -ComputerName "dhcpserver" -ScopeId $ScopeID.scopeid | 
where {$_.hostname -match "hostname"}}