I have a list of domains from which I need a list of name servers for each domain and the IP addresses of the name servers.
Formatting / A better way?
Resolve-DnsName google.com -Type NS -DnsOnly | Select Name, NameHost, IP4Address
Name NameHost IP4Address
---- -------- ----------
google.com ns1.google.com
google.com ns4.google.com
ns4.google.com 216.239.38.10
ns1.google.com 216.239.32.10
I've cut the result down a bit. I would like the IP Address to appear on the same line as the rest of the data. A quick google showed me how to add a hash to the existing object.
$dl = gc C:\domains.txt
$result = $dl |
Resolve-DnsName -Type NS -DnsOnly |
Where { $_.IP4Address -like '' } |
Select Name, NameHost, @{l="IPAddress";e={Resolve-DnsName google.com -Type A | Select -ExpandProperty IPAddress}}
So for the above, is this the 'correct / best way' or would you recommend something else.
Secondly, some of the results fail with lots of red, the important bit of information that I'd like to capture is 'DNS name does not exist', 'DNS server failure', there are a couple of others. How do I catch the relevant error, I assume I can add it to an new hash 'column'. I can't think of a way to use a try, catch block in my code?
Capture the results to a variable so that you don't have to perform the query multiple times. The data from the variable can be used to slice and dice anyway you want.
If you have lots of hostnames to query just put the entire block below in a foreach
loop.
$name = 'google.com'
try{
$dns = Resolve-DnsName -Name $name -Type NS -DnsOnly -ErrorAction Stop
$IPhash = @{}
$dns |
Where-Object Section -eq Additional |
ForEach-Object {
$IPhash.Add($_.name, $_.IP4Address)
}
$dns |
Where-Object Section -eq Answer |
Sort-Object NameHost |
Select-Object Name, NameHost,
@{N='IP'; E={$IPhash[$_.NameHost]}},
@{N='Status'; E={'Resolved'}}
} Catch{
[pscustomobject]@{
Name = $name
NameHost = ''
IP = ''
Status = $Error[0].Exception.Message
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With