Author Posts

September 29, 2015 at 2:39 am

I'm writing a very simple script to resolve DNS records with the Resolve-DnsName cmdlet. But I can't get the error handling to work.

The error

Resolve-DnsName : HOSTNAME : DNS name does not exist
At line:6 char:17
+ Resolve-DnsName $node -Type A | FT Name,IPAddress
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ResourceUnavailable: (HOSTNAME:String) [Resolve-DnsName], Win32Exception
+ FullyQualifiedErrorId : DNS_ERROR_RCODE_NAME_ERROR,Microsoft.DnsClient.Commands.ResolveDnsName

Details about the error

PS C:\> $error[0] | fl * -Force
writeErrorStream : True
PSMessageDetails :
Exception : System.ComponentModel.Win32Exception (0x80004005): HOSTNAME : DNS name does not exist
at Microsoft.DnsClient.Commands.win32.GetDNSRecords(String QueryName, String[] DnsServerIPs, QueryOptions Options, RecordType Type)
at Microsoft.DnsClient.Commands.api.SendDnsQuery(Cmdlet HostCmdlet, String NameQueried, RecordType DNSQueryType, String[] DNSServerAddresses,
QueryParameters Switches)
TargetObject : HOSTNAME
CategoryInfo : ResourceUnavailable: (HOSTNAME:String) [Resolve-DnsName], Win32Exception
FullyQualifiedErrorId : DNS_ERROR_RCODE_NAME_ERROR,Microsoft.DnsClient.Commands.ResolveDnsName
ErrorDetails :
InvocationInfo : System.Management.Automation.InvocationInfo
ScriptStackTrace : at , : line 6
PipelineIterationInfo : {0, 1, 0}

The catch script block:

catch [System.ComponentModel.Win32Exception]
{
write-Warning "$node is not in DNS"
}

Running a normal catch without the exception class won't work either.
Does anyone know a way around this?

September 29, 2015 at 3:01 am

try to use [System.Net.DNS]::Resolve($node) instead of Resolve-DnsName

September 29, 2015 at 3:17 am

One way you can do this is to set the $erroractionpreference variable

$eap = $ErrorActionPreference
$ErrorActionPreference = 'Stop'
try {
Resolve-DnsName W12R2DSC3 -Server server02
}
catch {
  throw 'Record not found'
}
$ErrorActionPreference = $eap

September 29, 2015 at 3:31 am

Actually I've just done a bit more testing and this works

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