Tuesday, April 14, 2015

Use Powershell to Change Host's FQDN / Suffix

I'm attempting to setup 6 Windows Server 2012 R2 RDP Session Host servers all via the CLI using PowerShell.

When it came time to configure the machine's name, domain, and Primary FQDN, I could rename the computer (Rename-Computer), add it to a domain (Add-Computer), but I got stuck trying to update / change the Primary DNS suffix of this computer, as there was no way I could find - other than using ancient netdom.exe, not my idea of PowerShell.

I hacked around with this for a bit on some Windows Server 2012 R2 servers modifying the registry to make it happen. Updating Domain and NV Domain in the [HKLM\System\CurrentControlSet\Services\Tcpip\Parameters] initially seemed to work with no issue - https://technet.microsoft.com/en-us/library/aa998420%28v=exchg.80%29.aspx.

Later, I discovered that the SPN record information for AD computers also needed to be updated or you get "The security database on the server does not have a computer account for this workstation trust relationship" error.

Below is what I have been using and is seems to work, as long as it is Run as Administrator as a Local Administrator and from a Domain Admin account (if connected to an AD domain.)

Current version at https://github.com/cajeeper/PowerShell/blob/master/Update-HostFQDN.ps1

Latest change: Added updating the dnsHostName attribute - Thanks to Nan Zhang

$computerName = $env:computername

$DNSSuffix = "abc.com"

$oldDNSSuffix = (Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\" -Name "NV Domain")."NV Domain"

#Update primary DNS Suffix for FQDN
Set-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\" -Name Domain -Value $DNSSuffix
Set-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\" -Name "NV Domain" -Value $DNSSuffix

#Update DNS Suffix Search List - Win8/2012 and above - if needed
#Set-DnsClientGlobalSetting -SuffixSearchList $oldDNSSuffix,$DNSSuffix

#Update AD's SPN records for machine if part of an AD domain
if ((gwmi win32_computersystem).partofdomain -eq $true) {
     $searchAD = new-object System.DirectoryServices.DirectorySearcher
     $searchAD.filter = "(&(objectCategory=computer)(cn=$($computerName)))"
     $searchADItem = $searchAD.FindAll() | select -first 1
     $adObj= [ADSI] $searchADItem.Path
     $oldadObjSPN = $searchADItem.Properties.serviceprincipalname
     $adObj.Put('serviceprincipalname',($oldadObjSPN -replace $oldDNSSuffix, $DNSSuffix))
     $oldadObjDNS = $searchADItem.Properties.dnsHostName
     $adObj.Put('dnsHostName',($oldadObjDNS -replace $oldDNSSuffix, $DNSSuffix))
Formatted for web with http://codeformatter.blogspot.com/ 

Before changing DNS Suffix via CLI / PowerShell

Ran CLI / PowerShell script to update Primary DNS Suffix

After Running CLI / PowerShell script

Upward and onward!