<#
Solution: Hydration 
Purpose: Configure - DNS Zone Inverse
Version: 1.2 -  Juin 2015 

Author - Jérôme Bezet-Torres
 
#>

# Determine where to do the logging 
$tsenv = New-Object -COMObject Microsoft.SMS.TSEnvironment 
$logPath = $tsenv.Value("LogPath") 
$logFile = "$logPath\$($myInvocation.MyCommand).log" 

# Start the logging 
Start-Transcript $logFile 
Write-Host "Logging to $logFile"

###Declaration Variables###

$a = Get-NetIPAddress -InterfaceAlias Ethernet* -AddressFamily IPv4
$IP=$a.IPAddress
$IPv4=$IP.split(".")
$IP1=$IPV4[0]
$IP2=$IPV4[1]
$IP3=$IPV4[2]
$IP4=$IPV4[3]
$info=get-addomain
$FQDN=$info.DNSRoot
$split=$FQDN.split(".")
$domain=$split[0]
$Ext=$split[1]
$zone= $info.Forest
$SRVDNS=$info.InfrastructureMaster
$records2 = New-Object System.Collections.ArrayList
$Netbios=$SRVDNS.Split(".")
$NetbiosDC=$Netbios[0]
 
###Fin Variables###

$networkID = "$IP1.$IP2.$IP3.0/24"
$test1= Get-DnsServerZone -ComputerName $NetbiosDC
# Crétaion des Zones de recherches inversées

if ($test1.ZoneName -contains "$IP3.$IP2.$IP1.in-addr.arpa")
{
    Write-Host "DNS Zone Already exist" -ForegroundColor Yellow 
}
else
{
   Add-DnsServerPrimaryZone -NetworkID $networkID -ZoneFile "$IP3.$IP2.$IP1.in-addr.arpa.dns" -ComputerName $NetbiosDC 
}

# Ajout des enregistrements PTR

$records = Get-DnsServerResourceRecord -ZoneName $zone -ComputerName $SRVDNS -RRType A 
foreach ($item in $records)
{
    
    if(!$item.HostName.Equals("@") -and !$item.HostName.Equals("DomainDnsZones")-and !$item.HostName.Equals("ForestDnsZones")){

        $records2.Add($item)|Out-Null
    }
}


foreach ($item in $records2)
{
$info=get-addomain
$FQDN=$info.DNSRoot
$PTR = $item.HostName
$IPO4= $item.RecordData
$t=$ipo4.IPv4Address
$IPN4=$t.IPAddressToString.Split(".")
$octet4 = $IPN4[3]
$test2= Get-DnsServerResourceRecord -ZoneName "$IP3.$IP2.$IP1.in-addr.arpa" -ComputerName $SRVDNS -RRType Ptr
    if ($test2 -eq $null)
        {
     Add-DnsServerResourceRecordPtr -Name "$octet4" -ZoneName "$IP3.$IP2.$IP1.in-addr.arpa"   -PtrDomainName "$PTR.$FQDN"  -ComputerName $NetbiosDC 
        }
    elseif ($test2.HostName -eq $octet4)
        {
           write-Host "PTR record Already exist" -ForegroundColor Yellow
        }
        else 
        {
         Add-DnsServerResourceRecordPtr -Name "$octet4" -ZoneName "$IP3.$IP2.$IP1.in-addr.arpa"   -PtrDomainName "$PTR.$FQDN"  -ComputerName $NetbiosDC 
        }
  
    
}

# Stop logging 
Stop-Transcript
