如何自定义DHCP所有作用域与租约脚本?三类修改需求咨询
PowerShell DHCP脚本修改方案
以下是满足你所有需求的修改后脚本:
$DHCPServers = Get-DhcpServerInDC $R = @() ForEach ($Server in $DHCPServers) { # 提取服务器短名称(去掉域名部分) $S = $Server.DnsName.Split('.')[0] $Scopes = Get-DhcpServerv4Scope –ComputerName $Server.DnsName ForEach ($Scope in $Scopes) { $AllScopes = $Scope.ScopeID.IPAddressToString $Results = Get-DhcpServerv4Lease -ComputerName $Server.DnsName -ScopeId $AllScopes -AllLeases | Select-Object @{Name="DHCPServer"; Expression={$S}}, ScopeId, @{Name="ScopeIdName"; Expression={$Scope.Name}}, # 添加作用域名称列 IPAddress, AddressState, ClientId, ClientType, HostName, Description, DnsRegistration, DnsRR, LeaseExpiryTime, NapCapable, NapStatus, PolicyName, ProbationEnds, ServerIP, PSComputerName $R += $Results } } # 按服务器、作用域IP、客户端IP正确排序 $R | Sort-Object -Property DHCPServer, @{Expression={[ipaddress]$_.ScopeId}}, @{Expression={[ipaddress]$_.IPAddress}} | Out-GridView
关键修改说明:
- 添加ScopeIdName列:你之前错误使用了
$Scopes.Name,$Scopes是作用域集合,需引用当前循环的单个作用域对象$Scope.Name,才能正确匹配每个作用域的名称。 - 修复IP排序异常:字符串格式的IP会按字符顺序错误排序,将
ScopeId和IPAddress转换为[ipaddress]类型后,PowerShell会按IP地址的数值逻辑完成正确排序。 - 缩短服务器DNS名称:通过
$Server.DnsName.Split('.')[0]拆分完整DNS名称,取第一个元素得到短名称(如DC1.orginization.org转为DC1)。注意获取DHCP数据时仍使用完整DNS名称,避免短名称解析失败。
内容的提问来源于stack exchange,提问作者Zachary Jensen
相关产品推荐
相关产品推荐

