Created
September 6, 2024 17:23
-
-
Save djad442/bd7ed4cdecaa402b17641a2652962ede to your computer and use it in GitHub Desktop.
Powershell Script, Generate Active DHCP Leases
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Define the DHCP Server and the list of Scope IDs (Zones) | |
$dhcpServer = "MYSERVER" # Replace with the name or IP address of your DHCP server | |
$scopeIDs = @("10.2.0.0","10.3.0.0","192.168.0.0") # Add all subnets here | |
# Import the DHCP Server Module (in case it's not loaded) | |
Import-Module DhcpServer | |
# Function to convert lease time to Linux format, handling null values | |
function Convert-LeaseTime($leaseTime) { | |
if ($leaseTime -ne $null) { | |
return $leaseTime.ToString("yyyy/MM/dd HH:mm:ss") | |
} else { | |
# Handle null by setting a default time or skipping | |
return "2024/01/01 00:00:00" # Default to Unix epoch time for null values | |
} | |
} | |
# Output file for Linux DHCP leases | |
$outputFile = "C:\linux-dhcp-leases.txt" | |
# Clear the file if it exists, to avoid appending to old data | |
if (Test-Path $outputFile) { | |
Remove-Item $outputFile | |
} | |
# Process each scope and fetch leases | |
foreach ($scopeID in $scopeIDs) { | |
Write-Host "Processing leases for scope: $scopeID" | |
# Get the list of active leases for the specified scope | |
$leases = Get-DhcpServerv4Lease -ComputerName $dhcpServer -ScopeId $scopeID | |
# Process each lease and convert it into the Linux DHCP lease format | |
$leaseData = foreach ($lease in $leases) { | |
$leaseStartTime = Convert-LeaseTime($lease.AddressStateTime) | |
$leaseEndTime = Convert-LeaseTime($lease.LeaseExpiryTime) | |
@" | |
lease $($lease.IPAddress) { | |
starts $(($lease.AddressStateTime).DayOfWeek) $leaseStartTime; | |
ends $(($lease.LeaseExpiryTime).DayOfWeek) $leaseEndTime; | |
cltt $(($lease.AddressStateTime).DayOfWeek) $leaseStartTime; | |
binding state active; | |
next binding state free; | |
hardware ethernet $($lease.ClientId); | |
uid "$($lease.ClientId)"; | |
client-hostname "$($lease.HostName)"; | |
} | |
"@ | |
} | |
# Append the formatted data to the output file | |
$leaseData | Out-File -FilePath $outputFile -Append | |
} | |
Write-Host "Leases have been exported to $outputFile in Linux-compatible format, including hostnames." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment