Forum Discussion

Arlecchino's avatar
Arlecchino
Copper Contributor
May 07, 2025

need to create a PTR record via PS | Need your help !

Hello dear community,

I am trying to update PTR records in my DNS manager using PowerShell script and I am using the below script, it works only when a reverse zone is already existing but I have a part of the code to create a reverse zone if doesn't exist. So the problem is reverse zone is not being created and script ends.

Can anyone debug it for me ? or tell me what is wrong or I am ok to have a new script if the below is not right.

 

Appreciate your help !!! :)

-------------------------

param(
    [string]$CsvPath = "E:\dns test file.csv",
    [string]$DnsServer = "10.10.10.10"
)
 
# Import required module
try {
    Import-Module DnsServer -ErrorAction Stop
} catch {
    Write-Error "Failed to import DnsServer module: $_"
    exit 1
}
 
# Import CSV data
try {
    $records = Import-Csv -Path $CsvPath
    Write-Host "Successfully imported $($records.Count) records from $CsvPath"
} catch {
    Write-Error "Failed to import CSV: $_"
    exit 1
}
 
# Initialize counters
$results = @{
    Success = 0
    Failure = 0
    Skipped = 0
    Created = 0
}
 
# Process each record
foreach ($record in $records) {
    Write-Host "`nProcessing $($record.IPAddress) -> $($record.Hostname)"
    
    try {
        # Validate IP address format
        $octets = $record.IPAddress -split '\.'
        if ($octets.Count -ne 4) {
            throw "Invalid IP address format - must have 4 octets"
        }
        
# Build reverse zone name (e.g., 10.0.0.0/24 becomes 0.0.10.in-addr.arpa)
$reverseZone = "$($octets[2]).$($octets[1]).$($octets[0]).in-addr.arpa"
        $ptrName = $octets[3]  # Last octet becomes record name
        
        # Validate and format hostname
        $hostname = $record.Hostname.Trim()
        if (-not $hostname.EndsWith('.')) {
            $hostname += '.'
        }
        
        # Check if reverse zone exists
        $zoneExists = Get-DnsServerZone -Name $reverseZone -ComputerName $DnsServer -ErrorAction SilentlyContinue
        if (-not $zoneExists) {
            throw "Reverse zone $reverseZone does not exist on server $DnsServer"
        }
        
        # Check for existing PTR record
        $existingPtr = Get-DnsServerResourceRecord -ZoneName $reverseZone -ComputerName $DnsServer -Name $ptrName -RRType PTR -ErrorAction SilentlyContinue
        
        if ($existingPtr) {
            # Check if it already points to the correct host
            if ($existingPtr.RecordData.PtrDomainName -eq $hostname) {
                Write-Host "  [SKIP] PTR record already correctly points to $hostname"
                $results.Skipped++
                continue
            }
            
            # Update existing record
            Write-Host "  [UPDATE] Changing PTR from $($existingPtr.RecordData.PtrDomainName) to $hostname"
            $newRecord = $existingPtr.Clone()
            $newRecord.RecordData.PtrDomainName = $hostname
            
            Set-DnsServerResourceRecord -ZoneName $reverseZone -ComputerName $DnsServer `
                -OldInputObject $existingPtr -NewInputObject $newRecord -PassThru -ErrorAction Stop
            $results.Success++
        } else {
            # Create new record - FIXED SECTION
            Write-Host "  [CREATE] Adding new PTR record for $ptrName pointing to $hostname"
            
            # Explicitly create the record object
            $newPtrRecord = @{
                ZoneName = $reverseZone
                Name = $ptrName
                PtrDomainName = $hostname
                ComputerName = $DnsServer
                ErrorAction = 'Stop'
            }
            
            # Add the record with verbose output
            $result = Add-DnsServerResourceRecordPtr @newPtrRecord -PassThru
            if ($result) {
                Write-Host "  [SUCCESS] Created PTR record:"
                $result | Format-List | Out-String | Write-Host
                $results.Created++
            } else {
                throw "Add-DnsServerResourceRecordPtr returned no output"
            }
        }
    } catch {
        Write-Host "  [ERROR] Failed to process $($record.IPAddress): $_" -ForegroundColor Red
        $results.Failure++
        
        # Additional diagnostic info
        Write-Host "  [DEBUG] Zone: $reverseZone, Record: $ptrName, Target: $hostname"
        if ($Error[0].Exception.CommandInvocation.MyCommand) {
            Write-Host "  [DEBUG] Command: $($Error[0].Exception.CommandInvocation.MyCommand)"
        }
    }
}
 
# Display summary
Write-Host "`nUpdate Summary:"
Write-Host "  Created: $($results.Created)"
Write-Host "  Updated: $($results.Success)"
Write-Host "  Skipped: $($results.Skipped)"
Write-Host "  Failed: $($results.Failure)"
 
# Return results for further processing if needed
$results

 

--------------

Output what I got:


Successfully imported  records from E:\dns test file.csv

Processing 10.0.0.10 -> test.test.sd6.glb.corp.local
  [ERROR] Failed to process 10.0.0.10: Reverse zone 0.0.10.in-addr.arpa does not exist on server 10.10.10.10
  [DEBUG] Zone: 0.0.10.in-addr.arpa, Record: 10, Target: test.test.sd6.glb.corp.local.

Update Summary:
  Created: 0
  Updated: 0
  Skipped: 0
  Failed: 1

Name                           Value                                                                                        
----                           -----                                                                                        
Created                        0                                                                                            
Skipped                        0                                                                                            
Failure                        1                                                                                            
Success                        0       




2 Replies

  • Andres-Bohren's avatar
    Andres-Bohren
    Steel Contributor

    Hi Arlecchino​ 

    You check if the Zone exists, but do not acutally create one if it does not exist...

     

    # Check if reverse zone exists
            $zoneExists = Get-DnsServerZone -Name $reverseZone -ComputerName $DnsServer -ErrorAction SilentlyContinue
            if (-not $zoneExists) {
                throw "Reverse zone $reverseZone does not exist on server $DnsServer"
            }

     

    • Arlecchino's avatar
      Arlecchino
      Copper Contributor

      Hi Andres-Bohren​,

       

      Probably you missed this part of the script. it is in else part of the script

       

      # Create new record - FIXED SECTION
                  Write-Host "  [CREATE] Adding new PTR record for $ptrName pointing to $hostname"
                  
                  # Explicitly create the record object
                  $newPtrRecord = @{
                      ZoneName = $reverseZone
                      Name = $ptrName
                      PtrDomainName = $hostname
                      ComputerName = $DnsServer
                      ErrorAction = 'Stop'
                  }

Resources