Powershell – Change DNS Server Entries on Adapter

I created this script to change DNS Server entries on 2012 R2 servers

#Script gets a servers ip details and change the DNS server entries on the adapter
$ServerName = "PC"
$DNSServerAddresses = "10.104.2.51,10.104.2.52,10.104.2.53,10.104.2.54" 

Write-Host  "Lets see if it is turned on $ServerName" -foreground green
$Test_Connection = (test-connection -Count 2 -ComputerName $ServerName -ErrorAction SilentlyContinue -WarningAction SilentlyContinue )
$Test_Connection

if ( $Test_Connection -eq $NULL)

{

Write-Host  "Cannot Ping $ServerName" -foreground Red
return

}

Else

{

Write-Host  "Can ping $ServerName so carrying on" -foreground green

}

        

        $CIMSessionA = New-CimSession -computername $ServerName 

        $ServerNetAdapter = Get-NetIPInterface  -AddressFamily ipv4  -InterfaceAlias Ethernet -CimSession $CIMSessionA

        # Count the number of interfaces returned as we only deal with one interface

        $count = 0

        foreach ($item in $ServerNetAdapter)

        {

        $count++  

        }

        if ($count -gt 1)

        {

        Write-Host "Too many Interfaces!!!"   -foreground red

        }

        else

        {

        if ($ServerNetAdapter.DHCP -eq "Disabled")

            {

            Write-Host "$ServerName network adapter is static" -foreground Green

            Write-Host "Current DNS settings:" -foreground Green

            $CurrentAdapaterSettings = Get-DNSClientServerAddress –InterfaceIndex $ServerNetAdapter.IfIndex  -CimSession $CIMSessionA

            $CurrentAdapaterSettings | Select |FT

            Set-DNSClientServerAddress –InterfaceIndex $ServerNetAdapter.IfIndex -ServerAddresses $DNSServerAddresses -CimSession $CIMSessionA

            Write-Host "New settings:" -foreground Green

            $CurrentAdapaterSettings = Get-DNSClientServerAddress –InterfaceIndex $ServerNetAdapter.IfIndex  -CimSession $CIMSessionA

            $CurrentAdapaterSettings | Select |FT

            Remove-CimSession $CIMSessionA 

 

            }

        else

            {

            Write-Host "$ServerName network adapter is on DHCP" -foreground yellow

            Get-DNSClientServerAddress –InterfaceIndex $ServerNetAdapter.IfIndex  -CimSession $CIMSessionA

            }

        } 

 

Leave a comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.