powershell 中使用 get-dhcpserverv4scopestatistics 命令可直接获取 dhcp 作用域实时剩余地址数,无需第三方工具;结合 foreach-object 遍历、阈值告警脚本及任务计划程序,实现每分钟自动监控与告警;支持指定 scopeid 快速查询单个作用域,并可通过 -computername 远程执行。
直接用 powershell 查 dhcp 作用域剩余地址数,关键不是“实时刷新界面”,而是抓准数据源 + 设置触发条件 + 快速定位瓶颈。windows 自带的 get-dhcpserverv4scopestatistics 就是核心命令,它返回每个作用域当前已用、空闲、使用率等真实数值,无需第三方工具。
用 Get-DhcpServerv4ScopeStatistics 看实时剩余数
这条命令不依赖日志或界面,直接从 DHCP 服务内存中读取当前状态,毫秒级响应:
Get-DhcpServerv4Scope | ForEach-Object {
$stat = Get-DhcpServerv4ScopeStatistics -ScopeId $_.ScopeId
[PSCustomObject]@{
ScopeName = $_.Name
ScopeId = $_.ScopeId
FreeAddresses = $stat.Free
InUse = $stat.InUse
PercentageInUse = $stat.PercentageInUse
}
}
运行后立即输出类似:
ScopeName ScopeId FreeAddresses InUse PercentageInUse OfficeNet 192.168.1.0 12 242 95 GuestWifi 192.168.2.0 187 67 26
一眼看出哪个作用域快耗尽(比如 OfficeNet 剩 12 个)。
每分钟自动检查并告警(轻量级实时监控)
把上面逻辑封装成脚本,配合 Windows 任务计划程序实现“准实时”:
- 新建脚本
Check-DHCP-Alert.ps1,内容如下:$threshold = 15 # 剩余地址少于15个时发警告 $scopes = Get-DhcpServerv4Scope | ForEach-Object { $stat = Get-DhcpServerv4ScopeStatistics -ScopeId $_.ScopeId if ($stat.Free -lt $threshold) { Write-Host "⚠️ 作用域 '$($_.Name)' 剩余地址仅 $($stat.Free) 个!" -ForegroundColor Red # 可在此加 Send-MailMessage 或企业微信 webhook } [PSCustomObject]@{ Name = $_.Name; Free = $stat.Free; Percent = $stat.PercentageInUse } } - 在任务计划程序中新建基本任务,触发器设为“每1分钟重复一次”,操作为“启动程序”→
powershell.exe,参数填-ExecutionPolicy Bypass -File "C:\Scripts\Check-DHCP-Alert.ps1"。
直接查单个作用域的剩余数(运维排查最快方式)
不需要遍历所有作用域?直接指定 ScopeId:
Get-DhcpServerv4ScopeStatistics -ScopeId 192.168.1.0 | Select-Object ScopeId, Free, InUse, PercentageInUse
适用于快速验证某网段是否真被占满,比打开 DHCP 控制台点三四次鼠标快得多。
注意事项:权限和远程执行
- 脚本必须在 DHCP 服务器本地运行,或通过
-ComputerName参数指定远程服务器(需开启 WinRM 并有管理员权限):Get-DhcpServerv4ScopeStatistics -ScopeId 192.168.1.0 -ComputerName dhcp-prod.corp.local
- 执行前确认账户对 DHCP 服务有读取权限(通常域管理员或本地 Administrators 组成员即可)。
不复杂但容易忽略











