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
—-                   —- —  ——- ——— A    1200 Answer

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”

This entry was posted in DNS, PowerShell v5, Windows Server 2012 R2. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s