Best way to pull specific values out of Netsh using Powershell
-
26. července 2012 18:39
Hi,
I am trying to pull the subnet and free addresses for each subnet from DHCP. I was looking to use netsh to obtain the information and then pull this in to PS to manipulate, and before I go off down a tunnel it would be great if someone could advise the best approach to pulling back the specific info I am looking for.
The command I am running to pull the info in to a variable is...
$scopes = netsh dhcp server <specific dhcp server> show mibinfo
The provides data similar to the following excerpt...
MIBCounts:
Discovers = 840.
Offers = 474.
Delayed Offers = 0.
Requests = 498.
Acks = 550.
Naks = 0.
Declines = 0.
Releases = 466.
ServerStartTime = 26 July 2012 14:29:40
Scopes = 16.
Scopes with Delay configured= 0.
Subnet = 192.168.1.0.
No. of Addresses in use = 0.
No. of free Addresses = 2.
No. of pending offers = 0.
Subnet = 192.168.2.0.
No. of Addresses in use = 0.
No. of free Addresses = 2.
No. of pending offers = 0.
Subnet = 192.168.3.0.
No. of Addresses in use = 0.
No. of free Addresses = 2.
No. of pending offers = 0.
I am not interested in the info at the start, just the IP subnets and the number of free addresses for each.
Any help will be much appreciated.
Kevin
Všechny reakce
-
26. července 2012 18:53
Like this?
$scopes = netsh dhcp server <specific dhcp server> show mibinfo $scopes -match 'Subnet = |No\. of free Addresses = '
[string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "
-
29. července 2012 9:30
The -match operator doesn't support regular expression options or multiple matching. But the [regex] type does. So if $a contains the netsh result, then:
$m = [regex]::Matches($a, 'Subnet = ([0-9.]+)\..*?No. of free Addresses = (\d+)', [System.Text.RegularExpressions.RegexOptions]::Singleline)
And $m.Count will tell you how many subnets are found. For each subnet $n in 0..($m.Count), $m[$n].Groups[1].Value is the IP and $m[$n].Groups[2].Value is the number remaining.
To support IPv6 as well as IPv4 change "[0-9.]+" in the first capture to "[0-9A-B:.]+".
Richard J Cox