PowerShell可实现DHCP租约实时监控:通过Get-DhcpServerv4Lease轮询获取租约,用Where-Object筛选Expired或超期Active异常,结合循环、利用率计算、日志导出及事件日志交叉验证,构建轻量级监控体系。
直接用 powershell 查看租约状态不难,关键是要“实时监控”——即持续获取、自动识别异常、及时响应。windows server 自带的 dhcp 模块支持轮询、筛选和导出,但需组合使用才能形成有效监控逻辑。
快速查看当前所有租约
运行以下命令可列出指定作用域下全部活跃租约:
Get-DhcpServerv4Lease -ScopeId 192.168.10.0
若要查全服务器所有作用域的租约,可用:
Get-DhcpServerv4Scope | Get-DhcpServerv4Lease
输出包含 IP 地址、客户端 ID(通常是 MAC)、租约到期时间、地址状态(Active/Expired/Released)等核心字段。
识别过期未释放或“僵尸 Active”租约
真实环境中最常卡住的是两类租约:已过期但状态仍是 Expired;或明明断网多日却仍标为 Active。这两类都会虚占地址池。
在 Windows 上执行终端命令,或对比 Windows 与 Linux 的 Shell 语法时使用。建议先检测当前 Shell 是 PowerShell 还是 cmd.exe,再给出相应命令……
- 查所有已过期(但尚未被清理)的租约:
Get-DhcpServerv4Lease | Where-Object {$_.AddressState -eq "Expired"} - 查疑似“僵尸 Active”租约(比如 7 天前就该到期却还显示 Active):
Get-DhcpServerv4Lease | Where-Object {$_.LeaseExpiryTime -lt (Get-Date).AddDays(-7) -and $_.AddressState -eq "Active"}
实现轻量级实时轮询监控
不需要第三方工具,用 PowerShell 循环+延时即可模拟实时盯控。例如每 5 分钟检查一次地址池利用率是否超 85%,并高亮异常租约:
$scope = "192.168.10.0"
while ($true) {
$leases = Get-DhcpServerv4Lease -ScopeId $scope
$used = $leases.Count
$total = (Get-DhcpServerv4Scope -ScopeId $scope).SubnetMask -replace '\.', '' | ForEach-Object { [math]::Pow(2, 32 - ($_ | Measure-Object -Character).Characters) } | Select-Object -First 1
$util = [math]::Round(($used / $total) * 100, 1)
if ($util -gt 85) { Write-Host "⚠️ 警告:作用域 $scope 利用率 $util%" -ForegroundColor Red }
Get-DhcpServerv4Lease -ScopeId $scope | Where-Object {$_.LeaseExpiryTime -lt (Get-Date).AddHours(-24)} | Select-Object IPAddress, ClientId, LeaseExpiryTime
Start-Sleep -Seconds 300
}
按 Ctrl+C 可随时中止。如需后台长期运行,可转为计划任务或 Windows 服务封装。
配合日志与导出做留痕分析
单次查询只是快照,加一句重定向就能生成时间戳日志,便于回溯对比:
Get-DhcpServerv4Lease -ScopeId 192.168.10.0 | Select-Object IPAddress, ClientId, AddressState, LeaseExpiryTime | Export-Csv -Path "C:\DHCP\Leases_$(Get-Date -Format 'yyyyMMdd_HHmm').csv" -NoTypeInformation
再配合任务计划程序,每天固定时刻执行,就能构建简易 DHCP 审计基线。结合事件日志(Event ID 10/11/14)交叉验证,定位耗尽原因更准。

















