New-DNSRecord

Uit Brakwiki
Ga naar: navigatie, zoeken
#############################################
##  Script Name: New-DNSRecord.ps1         ##
##  Author: Ben Brakband                   ##
##  Date: 30/07/2015, Version: 1.0         ##
#############################################

param (
    [Parameter(Mandatory=$true)][string]$CSVFile,
    $DNSServer = "net-dc01.net.local"
 )
#Set Log File
$LogTime = Get-Date -Format "dd-MM-yyyy_hh-mm-ss"
$LogFile = ".\LogFiles\DNS Log "+$LogTime+".log"
"DNS log; created @ $LogTime" | out-File $LogFile

#Check if all required parameters are given, if not display help and exit script
if ($CSVFile -eq "") {write-host "Syntax: New-DNSRecord -CSVFile <Filename>"; exit}

#Open CSV
$PolicyCSV = Import-Csv $CSVFile

foreach ($Line in $PolicyCSV) {
    $IPAddress = $Line.IP
    $Hostname = $Line.Hostname
    $Zone = $Line.Zone
    $Reverse = $line.Reverse
    Remove-Variable Recordnow -ErrorAction SilentlyContinue
    $Recordnow = Get-DnsServerResourceRecord -ZoneName $Zone -Name $Hostname -ComputerName $DNSServer -ErrorAction SilentlyContinue
    if ($Recordnow) {
       Write-host "Record $Hostname Already exists, deleting" -ForegroundColor Green
       remove-DnsServerResourceRecord -ZoneName $Zone -ComputerName $DNSServer -Name $Hostname -RRType A -Force
       
       #makePTR-zone
       $CurrentIP = $Recordnow.RecordData.IPv4Address.IPAddressToString
       $IPSplit = $CurrentIP.Split(".")
       $PTRZone = $IPSplit[2] + "." + $IPSplit[1] + "." + $IPSplit[0] + "." + "in-addr.arpa"
       remove-DnsServerResourceRecord -ZoneName $PTRZone -ComputerName $DNSServer -Name $IPSplit[3] -RRType Ptr -Force -ErrorAction SilentlyContinue
       "-- Removed existing Record for $Hostname from $Zone with Address $IPAddress" | out-File $LogFile -Append
       "-- Removed existing PTR Record for $Hostname from $PTRZone" | out-File $LogFile -Append
    }
    
     Write-Host "Create record $Hostname in Zone $Zone with $IPAddress" -ForegroundColor Green
     if (($Reverse -eq "yes") -or ($Reverse -eq "y")) {
          "++ Created Record $Hostname in Zone $Zone with Address $IPAddress, Including PTR Record" | out-File $LogFile -Append
          "++ Created PTR Record for $Hostname" | out-File $LogFile -Append
          Add-DnsServerResourceRecord -ZoneName $Zone -A -Name $Hostname -IPv4Address $IPAddress -ComputerName $DNSServer -CreatePtr -ErrorAction SilentlyContinue
          Write-Host "Create reverse lookup record: Yes"� -ForegroundColor Yellow
      } else {
          "++ Created Record $Hostname in Zone $Zone with Address $IPAddress" | out-File $LogFile -Append
          "Created Record $Hostname in Zone $Zone with Address $IPAddress" | out-File $LogFile -Append
          Add-DnsServerResourceRecord -ZoneName $Zone -A -Name $Hostname -IPv4Address $IPAddress -ComputerName $DNSServer -ErrorAction SilentlyContinue
          Write-Host "Create reverse lookup record: No"� -ForegroundColor Red
      }
    
  }