Changing DNS servers in static configuration

Tagged: 

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of Edward Panzeter Edward Panzeter 2 years, 4 months ago.

  • Author
    Posts
  • #16901
    Profile photo of Edward Panzeter
    Edward Panzeter
    Participant

    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?

    [hr]
    [i]

    $targets = Get-Content "E:\Powershell\Input\ServersTest.txt"
    $removeAddress = "1.1.1.3"
    $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
                $NIC.SetDNSServerSearchOrder($newDNS)
                $newDNS = $null
            }
            Else {
                $text = "No DNS changes made to " + $target + " for adapter " + $NIC.ServiceName + "`n"
                Add-Content -Path $filePath -Value $text
            }
            
        }
        "-------------------"
    }

    [/i]

  • #16910
    Profile photo of Mike F Robbins
    Mike F Robbins
    Participant

    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
      Profile photo of Edward Panzeter
      Edward Panzeter
      Participant

      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.