Windows,DHCP 服务器预留 - 查找空闲 IP 地址

Windows, DHCP Server Reservation - finding free IP address

我正在尝试编写一个脚本来查找(并稍后添加预留)DHCP 设备。我遇到的问题是只有一个范围,在这个范围内,我们手动划分为不同的 IP 范围,应在其中添加特定类型的设备。

例如范围 10.92.0.0/24 我们将范围分配为

10.92.0.10-20 适用于 iPhone 等。 10.92.0.10.50 Android 手机等

我知道脚本可以通过我提供给它的 IP 范围,并且要么获取 DHCP 预留,要么显示错误。我一直在想第一个Error可以作为免费IP

有什么想法吗? :)

    # Get DHCP Scope
$Start = 100
$End = 140
$DHCPServer = "dhcpserver.company.com"

# Find Free IP address
    #It can use to get DHCP reservation by IP and find the one which returns error - which can be used as the free one - loop done
    #Now how to tell it to stop when the error occures?
While ($Start -le $End) {
    $IP = "10.92.0.$Start"
    Write-Host "Reservation for: $IP" -ForegroundColor Cyan
    Get-DhcpServerv4Reservation -ComputerName $DHCPServer -IPAddress $IP
    $Start++
}

您可以将 Get-DhcpServerv4Reservation 的输出分配给一个变量,然后对其进行操作:

While ($Start -le $End) {
    $IP = "10.92.0.$Start"
    $reservation = Get-DhcpServerv4Reservation -ComputerName $DHCPServer -IPAddress $IP -ErrorAction SilentlyContinue

    if($reservation){
        Write-Host "Reservation for: $IP" -ForegroundColor Cyan
        $reservation
    }
    else {
        Write-Host "No reservation found for: $IP" -ForegroundColor Red
        break #comment out to continue through all IPs in Scope
    }

    $Start++
}

为什么不使用专用的 cmdlet Get-DhcpServerv4FreeIPAddress

Get-DhcpServerv4FreeIPAddress -ScopeId "192.168.1.0" -StartAddress "192.168.1.100" -EndAddress "192.168.1.140" -ComputerName "dhcpserver.company.com"