Note that there are some explanatory texts on larger screens.

plurals
  1. POPowershell foreach math issue. Sum is cumulative, not foreach server polled
    primarykey
    data
    text
    <p>Trying to script a daily "check" on DHCP usage. Pulling info from DHCP servers using netsh, looking at IP addresses in use and available, removing letters and delimiting characters so all I have left is the raw number of addresses. Then add them up to get total address pool size and finish with % in use. I've been futzing with this for a few days now, and finally got something I liked, but my math doesn't work right. Some remote sites have multiple scopes/subnets, and when trying to add those numbers into a per-server total, and instead it just adds addresses cumulatively. I think my problem is the final "foreach" in $u and $f, but I'm not sure how to fix it and get what I want. If I remove the final foreach, it works fine for single subnet sites but can't handle more on any one server. I hope that made sense. </p> <pre><code>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" </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload