Changing DNS servers in static configuration

This topic contains 2 replies, has 2 voices, and was last updated by  Edward Panzeter 3 years, 10 months ago.

  • Author
  • #16901

    Edward Panzeter

    I am working to retire a DNS server and would like to remove the address from any servers with it currently listed. Everything seems to run correctly with the exception of the actual application of the new DNSServerSearchOrder. I get a ReturnValue of 70 which refers to an invalid address so I assume the input going into the "SetDNSServerSearchOrder()" command is in the wrong format. Can anyone tell me how to appropriately format the $newDNS variable to successfully plug into "SetDNSServerSearchOrder" command?


    $targets = Get-Content "E:\Powershell\Input\ServersTest.txt"
    $removeAddress = ""
    $newDNS = $null
    $address = $null
    $filePath = "E:\Powershell\Output\DNSChangeLog.txt"
    $time = (Get-Date -Format "h:mm tt").ToString()
    $date = (get-date).ToString('MM/dd/yyyy')
    $removeAddress2 = "*" + $removeAddress + "*"
    New-Item -Path $filePath -ItemType File -Force
    Add-Content -Path $filePath -Value ($time + " on " + $date)
    ForEach($target in $targets) {
        $NICs = Get-WmiObject Win32_NetworkAdapterConfiguration -Computername $target | Where{$_.IPEnabled -eq "TRUE" -and $_.DHCPEnabled -eq $false}
        ForEach($NIC in $NICs) {
            $DNS = $NIC.DNSServerSearchOrder
            If($DNS -like $removeAddress2) {
                $newDNS = $DNS -replace $removeAddress
                $newDNS = $null
            Else {
                $text = "No DNS changes made to " + $target + " for adapter " + $NIC.ServiceName + "`n"
                Add-Content -Path $filePath -Value $text


  • #16910

    Mike F Robbins

    The problem is with this line:

    $newDNS = $DNS -replace $removeAddress

    $newDNS is an array if the machine had two DNS server entries set. After that line runs, the array has one empty element and a second element that contains the DNS server's IP address you want to keep.

    Change that line to the following so it only has the DNS server's IP address you want to keep:

    $newDNS = $DNS | Where-Object {$_ -ne $removeAddress}
    • #16919

      Edward Panzeter

      Ah! That got me on the right road. I actually had to add the line

      $newDNS = $DNS.Split(" ") | Where-Object {$_ -ne $removeAddress}

      to the script since it was taking $DNS as just one string and not splitting it apart. Perfect! Thank you!

You must be logged in to reply to this topic.