I have looked around for a solution to this but haven't found anything good yet. I need to extract the DNS Servers from the output of the command ipconfig /all in a powershell script. What would be the best way to pull out this info?
Example:
Lease Expires . . . . . . . . . . : Monday, August 6, 2018 12:46:13 PM
Default Gateway . . . . . . . . . : fe80::200:5eff:fe00:204%4
10.161.180.1
DHCP Server . . . . . . . . . . . : 10.221.228.17
DHCPv6 IAID . . . . . . . . . . . : 115363651
DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-22-DE-E5-35-E0-4F-43-29-6E-21
DNS Servers . . . . . . . . . . . : 10.50.50.50
10.50.10.50
NetBIOS over Tcpip. . . . . . . . : Enabled
I need to pick the 2 IP's 10.50.50.50 and 10.50.10.50.
You could use a Regex like this:
"DNS Servers[ .]+:\s+(?<DNS1>\d\d?\d?\.\d\d?\d?\.\d\d?\d?\.\d\d?\d?)\s*(?<DNS2>\d\d?\d?\.\d\d?\d?\.\d\d?\d?\.\d\d?\d?)?"
This article has several examples of using Regular Expressions from PowerShell: https://kevinmarquette.github.io/2017-07-31-Powershell-regex-regular-expression/
Here's how it would likely solve your question:
$result = ipconfig /all
$groups = [regex]::matches($result, "DNS Servers[ .]+:\s+(?<DNS1>\d\d?\d?\.\d\d?\d?\.\d\d?\d?\.\d\d?\d?)\s*(?<DNS2>\d\d?\d?\.\d\d?\d?\.\d\d?\d?\.\d\d?\d?)?")[0].Groups
To get the first result (DNS1), use $groups[1].Value
and for the second (DNS2) use $groups[2].Value
. The result would look like:
$groups[1].Value -> 10.50.50.50
$groups[2].Value -> 10.50.10.50