header image

Error handling for DNS lookups

Posted by: | September 29, 2015 Comments Off on Error handling for DNS lookups |

Interesting question on the forum regarding the Resolve-DNSname cmdlet. This is part of the DNSclient module introduced with Windows 8.

 

If the DNS record is found everything is good

£> Resolve-DnsName W12R2DSC -Server server02 | ft -a

Name                   Type TTL  Section IPAddress
—-                   —- —  ——- ———
W12R2DSC.Manticore.org A    1200 Answer  10.10.54.204

 

If the record isn’t found you get an error

£> Resolve-DnsName W12R2DSC3 -Server server02
Resolve-DnsName : W12R2DSC3 : DNS name does not exist
At line:1 char:1
+ Resolve-DnsName W12R2DSC3 -Server server02
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceUnavailable: (W12R2DSC3:String) [Resolve-DnsName], Win32Exception
    + FullyQualifiedErrorId : DNS_ERROR_RCODE_NAME_ERROR,Microsoft.DnsClient.Commands.ResolveDnsName

 

If you want to gracefully handle that error you use try-catch

 

$computer = ‘W12R2DSC3’
try {
Resolve-DnsName $computer -Server server02 -ErrorAction Stop
}
catch {
  Write-Warning -Message "Record not found for $computer"
}

under: DNS, PowerShell v5, Windows Server 2012 R2

Comments are closed.

Categories