Updating DNS alias using Powershell

Hello Folks, today we will talk a little bit about updating DNS alias record.
Recently I want to change DNS alias record name to the new one, however doing it manually is not possible.
Alias name field is not editable, there is only an option to change target host.

 
It’s also not possible directly from powershell, but I’ve created a function which will:
automatically delete old record,
copy the name of the target host from old record,
create new alias with target host taken from old alias.

Using Powershell it’s much quicker than do it in manual way, so I strongly recommend to check below function.

function Update-DNSAliasRecord {
    
    [CmdletBinding()]
    param(
    [Parameter(Postion=0,HelpMessage="New DNS alias",Mandatory=$true,ValueFromPipeline=$true)] 
    [string]
    $NewDNS,
    [Parameter(Postion=1,HelpMessage="Old DNS alias",Mandatory=$true,ValueFromPipeline=$true)] 
    [string]
    $OldDNS,
    [Parameter(Postion=2,HelpMessage="Zone name of the alias",Mandatory=$true,ValueFromPipeline=$true)] 
    [string]
    $ZoneName
    )

    $ZoneNameLength = ($ZoneName.Length+1)
    $OldDNSShort = $OldDNS.Substring(0,$OldDNS.Length-$ZoneNameLength)
    $NewDNSShort = $NewDNS.Substring(0,$NewDNS.Length-$ZoneNameLength)

    Try
    {
        Write-Host Curent DNS record:
        Get-DnsServerResourceRecord -Name $OldDNSShort -ZoneName $ZoneName
    }
    Catch
    {
        $Exception = $_.exception.Message
        Write-Warning "Current DNS alias record can not be found. Following error occured: $Exception"   
    }
    
    $DNSRecordAlias = (Get-DnsServerResourceRecord -Name $OldDNSShort -ZoneName $ZoneName).RecordData.HostNameAlias
    $HostName = $DNSRecordAlias.Substring(0,$Computer.Length-1)

    Try
    {
        Remove-DnsServerResourceRecord -Name $OldDNSShort -ZoneName $ZoneName -RRType CName -Force
        Write-Host Old alias $OldDNS has been removed
    }
    Catch
    {
        $Exception = $_.exception.Message
        Write-Warning "Change of DNS Alias failed. Following error occured: $Exception"
    }

    Try
    {
        Add-DnsServerResourceRecord -ZoneName $ZoneName -HostNameAlias $HostName -CName -Name $NewDNS 
        Write-Host New alias $NewDNS has been created
    }
    Catch
    {
        $Exception = $_.exception.Message
        Write-Warning "Change of DNS Alias failed. Following error occured: $Exception"
    }

    Try
    {
        Get-DnsServerResourceRecord -Name $NewDNSShort -ZoneName $ZoneName
        Write-Host "Alias has been updated sucessfully!"
    }
    Catch 
    {
        $Exception = $_.exception.Message
        Write-Warning "Change of DNS Alias failed. Following error occured: $Exception"
    }
}

I hope that it will be usefull for some of you 🙂
Enjoy!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.