Thursday, February 26, 2015

Script for clear cache on DNS Servers in Domain (Domain Controllers)

Sometimes you need to change to the DNS server is very fast to apply. I want to share with you a script that will help to make clear the cache DNS quickly.
1. Clear the cache for all domain controllers of the domain (clear_dns_cache_domain.ps1)

$DomainContext = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext("Domain", "hq.contoso.com")
$objDomain = [System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($DomainContext)
foreach ($DC in $objDomain.DomainControllers.name)
{
    $Error.Clear()
    write-host $DC " start clear"
    $cache = Get-WmiObject -Namespace root/MicrosoftDNS -ComputerName $DC -query "Select * From MicrosoftDNS_Cache"
    $cache.ClearCache()
    if ($Error) { write-host $DC " fail clear" -fore Yellow }
    else { write-host $DC " cleared" -fore green }
}

2. Clear the cache for all domain controllers in one forest (clear_dns_cache_forest.ps1)

$ForestContext = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext("Forest", "contoso.com")
$objForest = [System.DirectoryServices.ActiveDirectory.Forest]::GetForest($ForestContext)
foreach ($Domain in $objForest.Domains)
{
    foreach ($DC in $Domain.DomainControllers.name)
    {
        $Error.Clear()
        write-host $DC " start clear"
        $cache = Get-WmiObject -Namespace root/MicrosoftDNS -ComputerName $DC -query "Select * From MicrosoftDNS_Cache"
        $cache.ClearCache()
        if ($Error) { write-host $DC " fail clear" -fore Yellow }
        else { write-host $DC " cleared" -fore green }
    }
}