My script reads a file with the List of DNS entries and then it replicates those DNS entries to a set of target DNS servers from the source DNS server where the DNS changes were made, so that those updates are seen on those sites quickly.
I would like some assistance on how to make this code more efficient so that it could execute faster
$CurrentDirectory = split-path -parent $MyInvocation.MyCommand.Definition #Set Command Path
#Clearing the DNS Server and Client CACHE
Clear-DnsClientCache
Clear-DnsServerCache -Force
$flag = 1
#CSV file with the DNS entries that need to be replicated
$HostNames = Import-Csv $CurrentDirectory\..\Config\DNS.csv
#Filter out a subset of the DNS servers that need to be updated
$DNSServers = resolve-dnsname -Type -- NS $Comp.Source_Domain | where {$_.name -contains $Comp.Source_Domain} | select namehost | where {$_.namehost -match 'rco|sto|poz|hyd|che'} | where {$_.namehost -notmatch $Comp.DC}
foreach ($Hostname in $HostNames) {
try {
$DSN = ""
$DSN = Get-DnsServerResourceRecord -Name $Hostname.Source_Name -ZoneName $Hostname.Source_Domain -RRType $Hostname.Source_Type -ComputerName $Hostname.DC | select -ExpandProperty distinguishedname -ErrorAction Stop
if($DSN -eq $null) { throw "Record Does Not Exist" }
foreach($DNSServer in $DNSServers) {
try{ Sync-ADObject -object $DSN -source $Hostname.DC -Destination $DNSServer.NameHost ;Write-Host $DNSServer }
Catch [Exception] { Write-Output "Unable to SYNC Object for $($Hostname.Source_Name) , From $($Hostname.DC) to $($DNSServer.NameHost) Failed With $($_.Exception.GetType().Fullname) - $($_.Exception.Message) - $($_.CategoryInfo.Category) " | Out-File $CurrentDirectory\ERROR.txt -Append }
}
}
Catch [Exception] {
Write-Output "$($Hostname.Source_Name) Lookup failed on $($Hostname.DC) Exception $($_.Exception.GetType().Fullname) - $($_.Exception.Message) - $($_.CategoryInfo.Category) " | Out-File $CurrentDirectory\ERROR.txt -Append
}
finally {}
}