다음을 통해 공유


How to force a DHCP database cleanup for expired leases in a specific scope

When a DHCP lease expires, it does not get removed immediately. This is because it becomes eligible for removal from DHCP database only after the grace period is over (By default four (4) hours). When a DHCP scope is not properly designed, DHCP users will not be able to connect to the network if no IP address is available. Similar situations might occur especially with very dynamic DHCP scopes (Example: DHCP scopes used for Wifi). The permanent fix would be to review the number of IPs assigned via the DHCP scope but an administrator would need to plan the change before making it in production.

When a DHCP scope no longer has available IP addresses, there is a workaround to force expired leases to be removed so that the IP addresses can be re-assigned. This could be done by combining Get-DhcpServerv4Lease (or Get-DhcpServerv6Lease for IPv6) and Remove-DhcpServerv4Lease (or Remove-DhcpServerv6Lease) cmdlets.

You can use the script below to force the cleanup for a specific scope (You will need to replace $computername variable value with the server name and $scopeid with the IP address of the DHCP scope):

$computername = "Server1"

$scopeid = "x.x.x.x"

foreach ($object in Get-DhcpServerv4Lease -ComputerName $computername -ScopeId $scopeid)

{

      if ($object.leaseExpiryTime -le (Get-Date))

      {

            $object.hostname

            Remove-DhcpServerv4Lease -ComputerName $computername -IPAddress ($object.IPAddress).IPAddressToString

      }

}

The script will get all DHCP leases within the scope, identify the expired ones and then will remove them. Once freed, the IP addresses can be re-assigned.

Important Remark: The shared script can be used as a workaround when clients are not able to connect because no more IP addresses are available within the DHCP scope. However, duplicate IP addresses problems might occur as the grace period is not applied. The workaround has been tested in a real production environment with no identified issues when applied.