POWERSHELL: Update DNS Settings On Remote Systems

#------------begin script-----------------------------

$TimeStamp = Get-Date -UFormat "%Y%m%d-%H%M"               # Get date/time stamp of script runtime
$ScriptPath = Split-Path $MyInvocation.MyCommand.Path      # Path of the script
$oldDNS     = "192.168.1.21"                               # DNS Server to replace
$newDNS     = "192.168.1.41"                               # replacement DNS Server
$List       = $ScriptPath + "\servers.txt                  # Input File containing the list of servers
$log        = New-Item -ItemType file -Path $ScriptPath -name change_DNS_$TimeStamp.csv -Force        # Log File

Add-Content -Path $log -Value "Servers,State"

[array]$List = get-content $List 
for($i=0; $i -lt $List.Length; $i++) 
{
    $Server = $List[$i]
    Write-Progress -Activity "Changing the DNS entries for " -Status "Server: $Server"
    if (Test-Connection -ComputerName $Server -Quiet) 
    {
        $colItems = get-wmiobject -class "Win32_NetworkAdapterConfiguration" -namespace "root\cimv2" -computername $Server | Where-Object {$_.IPEnabled -eq "True"}
            foreach ($objItem in $colItems)
            {
                $strDNSServerSearchOrder = $objItem.DNSServerSearchOrder
                $dnsexists = $strDNSServerSearchOrder -Contains $oldDNS
                if ($dnsexists -eq "True")
                {
                    $newArrDNS = $strDNSServerSearchOrder -replace ($oldDNS,$newDNS)
                    $objItem.setDNSServerSearchOrder($newArrDNS) | out-null
                    Add-Content -Path $log -Value "$($Server),OK"
                }
                else 
                {
                     Add-Content -Path $log -Value "$($Server),No concerns"
                }
            }
    }
    else 
    {
        Add-Content -Path $log -Value "$($Server),Offline"
    }
}

#------------End script--------------------------

No comments:

Post a Comment