Help Parsing NETSH DHCP Output
hello powershell guru's. starters not proficient scripting , getting started powershell (that disclaimer). have need parse output of "netsh dhcp server show optionvalue" command retrieve ip addresses option 6 dns servers. sample of output listed below.
my ultimate goal parse output retrieve ips of dhcp global dns servers (option 6) dhcp servers in enterprise (~260 servers). use informtion build netsh command repopulate option 6 value on dhcp servers updated entries.
one thing note entries option 6 may vary in servers may have couple , others may have 5 or 6 entires.
any ideas helpful. if there wmi access dhcp servers...
also wanted add able select-string regex , pull out ips of course grabbed of them need option 6 values.
select-string -path c:\temp\dhcpoptions.txt -pattern "[1-2]{0,1}[0-9]{1,2}\.[1-2]{0,1}[0-9]{1,2}\.[1-2]{0,1}[0-9]{1,2}\.[1-2]{0,1}[0-9]{1,2}" | fl
sample output:
dhcp standard option : general option values: optionid : 46 option value: number of option elements = 1 option element type = byte option element value = 8 optionid : 15 option value: number of option elements = 1 option element type = string option element value = somedomain.com optionid : 6 option value: number of option elements = 4 option element type = ipaddress option element value = 192.168.0.10 option element value = 192.168.0.123 option element value = 10.45.34.12 option element value = 10.3.24.5 optionid : 44 option value: number of option elements = 2 option element type = ipaddress option element value = 10.26.193.199 option element value = 10.4.50.203 command completed successfully.
try script, can further filter result piping output where-object:
# $d = netsh dhcp server show optionvalue # can parse netsh output directly
$d = get-content d:\scripts\temp\dhcpoptions.txt
$d = $d[3..($d.length-2)]
$itemposition= for($i=0;$i -le $d.length;$i++)
{
if($d[$i] -match 'optionid : \d+'){$i}
}
for($x=0; $x -lt $itemposition.count; $x++)
{
if($x -eq $itemposition.count-1)
{
$el = $d[$itemposition[$x]..($d.length-1)]
}
else
{
$el = $d[$itemposition[$x]..($itemposition[$x+1]-1)]
}
new-object psobject -property @{
optionid = [int]($el[0] -replace '\d')
optiontype = $el[3].split(' = ')[-1].trim()
optionvalue = ($el[4..($el.length)] | foreach-object { $_.split('=')[-1].trim() }) -join ','
}
}
# output
optionid optionvalue optiontype
-------- ----------- ----------
46 8 byte
15 somedomain.com string
6 192.168.0.10,192.168.0.123,10.45.34.... ipaddress
44 10.26.193.199,10.4.50.203 ipaddress
shay levy [mvp]
powershay.com
powershell toolbar
Windows Server > Windows PowerShell
Comments
Post a Comment