Can't seem to catch an error when trying to check if an AD domain exist.

Welcome Forums General PowerShell Q&A Can't seem to catch an error when trying to check if an AD domain exist.

This topic contains 2 replies, has 2 voices, and was last updated by

 
Participant
4 years, 1 month ago.

  • Author
    Posts
  • #23156

    Participant
    Topics: 40
    Replies: 73
    Points: 13
    Rank: Member

    I am running the following code and even when I use $ErrorActionPreference = 'STOP' and Try and Catch, I still cannot grab the error.

    $DomainName = "TestDomain"
    $DomainContext = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext("Domain", $DomainName)
    $Domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($DomainContext)
    $Root = $Domain.GetDirectoryEntry()
    $Root

    I simply want to be able to catch the following error that this will produce:

    Exception calling "GetDomain" with "1" argument(s): "The specified domain does not exist or
    cannot be contacted."
    At line:5 char:1
    + $Domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($DomainCo ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : ActiveDirectoryObjectNotFoundException

    Is there a way to do this so I can write-output, or write-warning messages myself to control what is displayed?

    Thanks

  • #23162

    Participant
    Topics: 2
    Replies: 90
    Points: 475
    Rank: Contributor

    This worked for me with, and without, a valid AD domain name, and I didn't need to modify the default error action.

    $DomainName = "NotADomain"
    try {
        $DomainContext = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext("Domain", $DomainName)
        $Domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($DomainContext)
        $Root = $Domain.GetDirectoryEntry()
        $Root
    } catch [System.Management.Automation.MethodInvocationException] {
        Write-Output -Verbose 'Error: The specified domain does not exist or cannot be contacted.'
    } catch {
        Write-Output -Verbose 'Error: Unspecified error.'
    }
    
  • #23163

    Participant
    Topics: 40
    Replies: 73
    Points: 13
    Rank: Member

    Great!

    That worked perfectly.

    Thank you very much for your help, it's much appreciated.

The topic ‘Can't seem to catch an error when trying to check if an AD domain exist.’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort