PowerShell – Export all DHCP Servers leases

Export all DHCP Servers leases

I used to save DHCP leases for IP infringement  access and needed to track mac address to find the user. this is a very good way to save the leases to easy lookup.



$dhcpServers = Get-DhcpServerInDC
$r = @()
$e = @()
Foreach ($server in $dhcpServers)
    {
        IF ($server.DnsName -like "RX*")
            {
                TRY
                    {
                        $s = $server.DnsName
                        $scopes = Get-DhcpServerv4Scope –ComputerName $s
                        foreach ($scope in $scopes)
                            {
                                $IPOfScope = $scope.ScopeID.IPAddressToString
                                $results =Get-DhcpServerv4Lease -ComputerName $s -ScopeId $IPOfScope -AllLeases | SELECT @{Name="DHCPServer"; Expression={$s}},HostName, AddressState, LeaseExpiryTime
                                $r += $results
                            }
                    }
                CATCH
                    {
                        $b  $error[0] | SELECT @{Name="ServerName"; Expression={$s}}, @{Name="ErrorType"; Expression={$_.Exception.GetType().FullName}}, @{Name="Error"; Expression={$_.Exception.Message}}
                        $e += $b
                    }
            }
    }
<# Output to CSV #>
$r #| Export-Csv -Path C:/temp/Results.csv
$e #| Export-Csv -Path C:/temp/Errors.csv