Powershell Error Handling

This topic contains 3 replies, has 3 voices, and was last updated by  Richard Siddaway 2 years, 2 months ago.

  • Author
    Posts
  • #30209

    Stian Myhre
    Participant

    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?

  • #30210

    Max Kozlov
    Participant

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

  • #30211

    Richard Siddaway
    Moderator

    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
    
  • #30212

    Richard Siddaway
    Moderator

    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"
    }
    

You must be logged in to reply to this topic.