Search code examples
powershelldnsactive-directoryzone

Getting DNS Records from an Active Directory zone by IP Addresses


I am trying to run the following query against my DNS zone to return records based on the IP addresses and having no luck, the script runs but just empty output.

Get-Content ip.txt| ForEach {
    Get-DnsServerResourceRecord -zonename "xxx.global" | where-object {$_.RecordData.ipv4address -eq "$_"}
}

The contents of the ip.txt file is like this:

"10.32.84.102"
"172.31.65.18"
"172.31.65.203"

I tried modifying my original command which works fine, but I want to run it against a list of IPs..

Get-DnsServerResourceRecord -zonename "xxx.global" | where-object {$_.RecordData.ipv4address -eq "10.32.84.102"}

Single line command works fine

What am i doing wrong?


Solution

  • You're using $_ to refer to different objects in your Where-Object.

    where-object {$_.RecordData.ipv4address -eq "$_"}
                 ^^^^                           ^^^^
    

    $_ is only set to one object at a time. If you start another pipeline, the previous value is going to be gone.

    You'll need to do something like this:

    $IPs = Get-Content ip.txt
    
    foreach ($IP in $IPs) {
        Get-DnsServerResourceRecord -zonename "xxx.global" | where-object { $_.RecordData.ipv4address -eq $IP }
    }
    

    You may also need to remove the double quotes from ip.txt. The IP is 10.32.84.102, not "10.32.84.102".