尝试编写每日“检查”DHCP使用情况的脚本。使用netsh从DHCP服务器中提取信息,查看正在使用和可用的IP地址,删除字母和分隔字符,这样我剩下的就是原始地址数。然后将它们添加到总地址池大小并使用%完成。我已经用这几天了,最后得到了我喜欢的东西,但我的数学运算不正常。某些远程站点具有多个范围/子网,并且在尝试将这些数字添加到每服务器总数时,而只是累积地添加地址。我认为我的问题是$ u和$ f的最终“foreach”,但我不确定如何修复它并得到我想要的东西。如果我删除最后的foreach,它适用于单个子网站点,但无法在任何一台服务器上处理更多。我希望这是有道理的。
function dhcp {
$servers = "contoso","contoso2","contoso3"
Foreach ($server in $servers)
{
netsh dhcp server \\$server show server
"DHCP Server: $server"
#netsh dhcp server \\$server show mibinfo | select-string -pattern "scope", "subnet", "No. of Addresses in use = ", "No. of free Addresses = "
$u = (netsh dhcp server \\$server show mibinfo |
where-object {$_-match "No. of Addresses in use = "} |
foreach-object{$_.Split(“=")[-1].Trim( ).Trim(".").Trim(" ")} |
foreach-object{($u2+=[int]$_)})
$f = (netsh dhcp server \\$server show mibinfo |
where-object {$_-match "No. of free Addresses = "} |
foreach-object{$_.Split(“=")[-1].Trim().Trim(".").Trim(" ")} |
foreach-object{($f2+=[int]$_)})
$total2 = ([int]$u2+[int]$f2)
$percent = [Math]::Round([int]$u2/[int]$total2*100,2)
"No. of Addresses in use = $u2"
"No. of free Addresses = $f2"
"Total Addresses: $total2"
"Percent in use: $percent%"
" ======"
"=================================================="
}
}
dhcp | out-file "C:\Users\crabbypatty\Desktop\Powershell\dhcplog $(get-date -f MM-dd-HHmm).txt"
答案 0 :(得分:1)
我通过在正则表达式中使用捕获组并使用切换条件处理正则表达式的能力来显着简化这一点。
哦,我会使用字典来确保每个服务器都是单独跟踪的,同时允许您在捕获完成后访问数据。如果您保存了数据,这也可以让您进行一些历史跟踪和比较......但是这超出了这个范围;)
e.g。
$addressesInUse = @{};
$addressesFree = @{};
foreach ($server in $serverList) {
$mibinfo = netsh dhcp server \\$server show mibinfo; #| where-object {$_-match "No. of Addresses in use = "} |
foreach ($info in $mibinfo) {
switch -regex ($info) {
"No. of Addresses in use = (?<count>\d+)" {
$val = $Matches["count"];
if ($addressesInUse.ContainsKey($server)) {
$addressesInUse.Add($server,$val);
} else {
$scopeCount.$server += $val;
}
break;
}
"No. of free Addresses = (?<count>\d+)" {
$val = [int]::Parse($Matches["count"]);
if ($addressesFree.ContainsKey($server)) {
$addressesFree.Add($server,$val);
} else {
$addressesFree.$server += $val;
}
break
}
}
}
}
foreach ($key in $addressesFree.keys) {
$total = $addressesInUse.$key + $addressesFree.$key;
$percent = [Math]::Round($addressesInUse.$server / $total*100,2)
Write-Host ("DHCP availablility for server {0}" -f $key);
Write-Host ("No. of Addresses in use = {0}" -f $addressesInUse.$key);
Write-Host ("No. of free Addresses = {0}" -f $addressesFree.$key);
Write-Host ("Total Addresses: {0}" -f $total);
Write-Host ("Percent in use: {0}%" - $percent);
}
答案 1 :(得分:0)
这可能就像在第一个循环的顶部将变量设置为零一样简单吗?在“netsh dhcp server \ $ server show server”之后的意思,将u2和f2都设置为零?
Foreach ($server in $servers) {
netsh dhcp server \\$server show server
"DHCP Server: $server"
此时,重置变量:
$f2 = 0
$u2 = 0