I’m looking at creating a script that clears out duplicate DHCP leases from our Windows Server 2008 R2 based DHCP server. I’ve found out that you can’t do this natively in PowerShell, but you can use PowerShell to call a netsh.exe command and then manipulate the data.
Command to list all DHCP leases:
netsh dhcp server 10.100.2.241 scope 10.100.0.0 show clients 1 The resulting output is a bit of a mess:
Changed the current scope context to 10.100.0.0 scope. Type : N - NONE, D - DHCP B - BOOTP, U - UNSPECIFIED, R - RESERVATION IP ============================================================================================ IP Address - Subnet Mask - Unique ID - Lease Expires -Type -Name ============================================================================================ 10.100.0.51 - 255.255.248.0 - 00-11-22-33-44-55 -24/05/2016 21:29:01 -D- WT008064807e32.domain.com 10.100.0.52 - 255.255.248.0 - 00-11-22-33-44-55 -24/05/2016 20:13:47 -D- EXT1054.domain.com 10.100.0.53 - 255.255.248.0 - 00-11-22-33-44-55 -24/05/2016 22:54:14 -D- EXT1018.domain.com 10.100.0.54 - 255.255.248.0 - 00-11-22-33-44-55 -24/05/2016 11:01:57 -D- V2040.domain.com 10.100.0.55 - 255.255.248.0 - 00-11-22-33-44-55 -24/05/2016 19:50:19 -D- V1041.domain.com ----SNIP---- As an example, the host V2119 is listed twice within the output with different IP addresses and Lease Expiry times:
V2119 - 10.100.6.45 - 24/05/2016 23:24:43 V2119 - 10.100.5.167 - 24/05/2016 23:06:21 In this example, I would delete 10.100.5.167 as it will expire earlier and is therefore the older lease and redundant.
Command to delete a specific lease by IP:
netsh dhcp server 10.100.2.241 scope 10.100.0.0 delete lease 10.100.5.167 I found this article, whereby the OP uses the output of the netsh command in PowerShell and then trims various bits to only return a list of hostnames and IPs. Although the result isn’t what I'm after, the trimming might come in handy. - https://theadminguy.com/2009/10/14/export-dhcp-leases-to-html-using-powershell/
Basically, I need a script to output all leases in DHCP, work out which hostnames are duplicated, then of those that are duplicated work out which is going to expire earlier and return the IP address and then pipe that into the netsh delete lease command above.
Any help you can give me on this would be amazing and hugely appreciated.
Give me a shout if you need anything clarifying.