In my last article I explained how to set the DNS IP addresses of remote computers and today I will show you how to get the DNS server IPs configured in network connections of local or remote computers using PowerShell.
Contents of this article

On servers, we use static IP configuration and static DNS configuration. If you have multiple sites in your environment, this list of DNS server IPs will vary from one site’s server to another. Given these, we sometimes end up with incorrect DNS IP entries in some of the servers. The script I am going to discuss will help you query all your servers and display their DNS server settings.

This script uses the Win32_NetworkAdapterConfiguration WMI class to get the DNS server IPs of all network adapters on the computer. This list of network adapters contains both physical and virtual adapters. We are only interested in adapters that have an IP address (DHCP/Static) because adapters without an IP address won’t have any DNS server settings.

As shown in the code below, I am using the Get-WmiObject cmdlet to query the Win32_NetworkAdapterConfiguration WMI class. I pass a filter with IPEnabled=TRUE to ensure I am querying the network adapters with a configured IP address. The –ComputerName parameter takes the computer name against which this WMI query will be executed. I placed the entire WMI query inside a try block to catch the errors.

try {
 $Networks = Get-WmiObject -Class Win32_NetworkAdapterConfiguration `
     -Filter IPEnabled=TRUE `
     -ComputerName $Computer `
     -ErrorAction Stop
 } catch {
  Write-Verbose "Failed to Query $Computer. Error details: $_"
  continue
}

After the WMI query executes, we get a list of network adapters that have a configured IP address. The next step is to iterate through them and find out the DNS server IP addresses. You can see that in the code below. The DNSServerSearchOrder parameter of each network connection contains the DNS server IP addresses. After reading the DNS server IP address parameters, I take the output through several tests to ensure that it is not empty (because it is quite possible that we configured static IP addresses and left the DNS server fields empty, either intentionally or by mistake) and to determine whether just one DNS server IP is configured. If the list of DNS server IP addresses is empty, I set the $PrimaryDNSServer and $SecondaryDNSServer variables to “Not set.” If only one DNS server is configured, I set the $SecondaryDNSServer variable to “Not set” and assign the DNS server IP value to $PrimaryDNSServer. Both of these variables will be set to appropriate DNS server IP address values if both DNS server IP addresses are available in the network adapter.

foreach($Network in $Networks) {
  $DNSServers = $Network.DNSServerSearchOrder
  $NetworkName = $Network.Description
 If(!$DNSServers) {
  $PrimaryDNSServer = "Notset"
  $SecondaryDNSServer = "Notset"
 } elseif($DNSServers.count -eq 1) {
  $PrimaryDNSServer = $DNSServers[0]
  $SecondaryDNSServer = "Notset"
 } else {
  $PrimaryDNSServer = $DNSServers[0]
  $SecondaryDNSServer = $DNSServers[1]
}

So far, we queried the required data and stored it in two variables ($PrimaryDNSServer and $SecondaryDNSServer). The next step is to create a custom PSObject to store the data and display it on the screen. The below code does exactly this:

$OutputObj = New-Object -Type PSObject
$OutputObj | Add-Member -MemberType NoteProperty 
  -Name ComputerName -Value $Computer.ToUpper()
$OutputObj | Add-Member -MemberType NoteProperty
  -Name PrimaryDNSServers -Value $PrimaryDNSServer
$OutputObj | Add-Member -MemberType NoteProperty 
  -Name SecondaryDNSServers -Value $SecondaryDNSServer
$OutputObj | Add-Member -MemberType NoteProperty 
-Name IsDHCPEnabled -Value $IsDHCPEnabled
$OutputObj | Add-Member -MemberType NoteProperty 
  -Name NetworkName -Value $NetworkName
$OutputObj

I query some more data, such as the description of the network adapter for easy identification of network connections that have DNS server IP addresses. I also populate another column in the output, called IsDHCPEnabled, to find out if the network adapter has DHCP given IP addresses or statically configured IP addresses.

Get DNS Server IP address with PowerShell

Get DNS Server IP address with PowerShell

Examples ^

· .\Get-DNSServers.ps1 – lists the DNS server IPs of network adapters on the local computer

· .\Get-DNSServers.ps1 -ComputerName TIBPC1 – lists the DNS server IPs of network adapters on the remote computer TIBPC1

· .\Get-DNSServers.ps1 -ComputerName TIBPC1, TIBPC2, TIBPC3 – lists the DNS server IPs of network adapters on multiple remote computers

· Get-Content c:\scripts\comps.txt | .\Get-DNSServers.ps1 – uses a text file called comps.txt to store the list of computers

Download the "Get DNS server IPs PowerShell" script: Get-DNSServers.ps1

+2
18 Comments
  1. Valentin 9 years ago

    So where is the script? I cannot see it anywhere?

    +2

  2. Valentine, that was my fault. I forgot the download link. You can find the link now at the end of the text. Thanks for the hint!

    0

  3. Author
    techibee.com 9 years ago

    Thanks for pointing that ,Valentin . Please share your feedback on the script.

    +1

  4. Paul 9 years ago

    This script didn't work for me. Is it supposed to be run against powershell v1 or v2?

    0

  5. Author
    techibee 9 years ago

    Hi, what is the error message? This script works perfectly in powershell v2.

    0

  6. Hi All, I have a list of mulitple servers in an excel. How can I amend the above script to query this list? I need to output an excel of all server in the server estate into an excel with the one colum of the primary, secondary DNS. This is my first post so please go easy!

    +1

  7. Wes 7 years ago

    Yes How do you run the script when using a list of servers

    0

  8. AndréSAramago 5 years ago

    Hello Michael!

    What would be necessary to change so that the script checks 3 DNS Server entries?

    PrimaryDNSServer

    SecondaryDNSServer and

    TertiaryDNSServer?

     

    Thank You!!!

     

    AS

    +3

  9. shyam 5 years ago

    i ran the script but I am not getting output

    what could be the reason ?

    0

  10. Scott 3 years ago

    Your script does not work.

    PS C:\scripts> C:\scripts\get-dnsservers.ps1

    At C:\scripts\get-dnsservers.ps1:1 char:1212

    + ... s) { $DNSServers = $Network.DNSServerSearchOrder $NetworkName = $Netw ...

    + ~~~~~~~~~~~~

    Unexpected token '$NetworkName' in expression or statement.

    At C:\scripts\get-dnsservers.ps1:1 char:1248

    + ... k.DNSServerSearchOrder $NetworkName = $Network.Description If(!$DNSSe ...

    + ~~

    Unexpected token 'If' in expression or statement.

    At C:\scripts\get-dnsservers.ps1:1 char:1296

    + ... NSServers) { $PrimaryDNSServer = "Notset" $SecondaryDNSServer = "Nots ...

    + ~~~~~~~~~~~~~~~~~~~

    Unexpected token '$SecondaryDNSServer' in expression or statement.

    At C:\scripts\get-dnsservers.ps1:1 char:1398

    + ... q 1) { $PrimaryDNSServer = $DNSServers[0] $SecondaryDNSServer = "Nots ...

    + ~~~~~~~~~~~~~~~~~~~

    Unexpected token '$SecondaryDNSServer' in expression or statement.

    At C:\scripts\get-dnsservers.ps1:1 char:1473

    + ... else { $PrimaryDNSServer = $DNSServers[0] $SecondaryDNSServer = $DNSS ...

    + ~~~~~~~~~~~~~~~~~~~

    Unexpected token '$SecondaryDNSServer' in expression or statement.

    + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException

    + FullyQualifiedErrorId : UnexpectedToken

     

    +2

  11. Krishna 3 years ago

    perfect, Hi can you let me know if I want to get default gateway information also, How can I modify these script?

    0

  12. Durga Prasad 3 years ago

    Hi, If I want to use for 1000+ servers this script is taking time, can you modify this script to use invoke-command? and

    add TertiaryDNSServer? also

    great script and explanation!

    0

    • @Durga

      This article is nearly 6 years old.

      With more recent environment (Windows 8 and Windows Server 2012 or later) you can use something like this:

      $ComputerList = @{
          'Computer1'
          'Computer2'
          'Computer3'
      }
      Invoke-Command -ComputerName $ComputerList -ScriptBlock {Get-NetIPConfiguration} -AsJob
      Get-Job | Wait-Job
      $Result = Get-Job | Receive-Job -Keep
      
      0

  13. Javier GP 3 years ago

    [cmdletbinding()]
    param ( [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
    [string[]]
    $ComputerName = $env:computername )
    begin {}
    process {
    foreach($Computer in $ComputerName)
    {
    Write-Verbose "Working on $Computer"
    if(Test-Connection -ComputerName $Computer -Count 1 -ea 0)
    {
    try {
    $Networks = Get-WmiObject -Class Win32_NetworkAdapterConfiguration ` -Filter IPEnabled=TRUE -ComputerName $Computer -ErrorAction Stop }
    catch { Write-Verbose "Failed to Query $Computer. Error details: $_" continue }
    foreach($Network in $Networks)
    {
    $DNSServers = $Network.DNSServerSearchOrder
    $NetworkName = $Network.Description
    If(!$DNSServers)
    {
    $PrimaryDNSServer = "Notset"
    $SecondaryDNSServer = "Notset"
    }
    elseif($DNSServers.count -eq 1)
    {
    $PrimaryDNSServer = $DNSServers[0]
    $SecondaryDNSServer = "Notset"
    }
    else
    {
    $PrimaryDNSServer = $DNSServers[0]
    $SecondaryDNSServer = $DNSServers[1]
    }
    If($network.DHCPEnabled)
    {
    $IsDHCPEnabled = $true
    }
    $OutputObj = New-Object -Type PSObject
    $OutputObj | Add-Member -MemberType NoteProperty -Name ComputerName -Value $Computer.ToUpper()
    $OutputObj | Add-Member -MemberType NoteProperty -Name PrimaryDNSServers -Value $PrimaryDNSServer
    $OutputObj | Add-Member -MemberType NoteProperty -Name SecondaryDNSServers -Value $SecondaryDNSServer
    $OutputObj | Add-Member -MemberType NoteProperty -Name IsDHCPEnabled -Value $IsDHCPEnabled
    $OutputObj | Add-Member -MemberType NoteProperty -Name NetworkName -Value $NetworkName
    $OutputObj
    }
    }
    else { Write-Verbose "$Computer not reachable" }
    }
    }
    end {}

    0

  14. Rufai 3 years ago

    Hello,

    I need to write a script that would show Computername, IP4 address, Location, OperatingSystem the two DNS server IP address on each system,

    Get-ADComputer -filter * -properties *|select Name, DNSHostName, OperatingSystem, Domain, Username, Userdomain, Firstseen, Lastseen, Chassis, Class, LastLogonDate, type, DC_type, Site, ipv4address, AssetName, Description | Export-Csv "c:\list_of_Device.csv"

    Meanwhile the above script generate the list of System with detail without DNS IP, am having issue to add the common that would generate DNS IPaddress for both Primary and secondary

    0

  15. A lot of those properties are not native to AD.. did you add your own?  And of course, some of these are user properties, and wouldn't "belong" to the computer object.   Or do you have an external source of data for some off those?

    You can use WMI to collect a lot of the information, and some of it would have to be retrieved from the AD object.  I also would not select all the properties on the Get-ADComputer.  Only retrieve what you actually need - it will speed up the retrieval, and your ability to sort/extract, etc.

    Also, what version of powershell do you have available?  This is a fairly complex set of data that has to be pulled from multiple sources.

    David F.

    +1
    avatar
  16. Stephen Sprencel 3 years ago

    Man, what a great script and write up!  This was exactly what I needed.  Thank you!

    0

  17. Joseph 11 months ago

    Hi All,

    Can we export this to a csv format ,

     

    can some one help me on this to be sorted out.

    0

Leave a reply to Harjot Kandola (Rank: )
Click here to cancel the reply

Please enclose code in pre tags

Your email address will not be published. Required fields are marked *

*

© 4sysops 2006 - 2021

CONTACT US

Please ask IT administration questions in the forums. Any other messages are welcome.

Sending

Log in with your credentials

or    

Forgot your details?

Create Account