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 Profile photo of I Am Sir Ask Alot I Am Sir Ask Alot 1 year, 9 months ago.

  • Author
    Posts
  • #23156
    Profile photo of I Am Sir Ask Alot
    I Am Sir Ask Alot
    Participant

    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:

    [blockquote]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[/blockquote]

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

    Thanks

  • #23162
    Profile photo of tommymaynard
    tommymaynard
    Member

    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
    Profile photo of I Am Sir Ask Alot
    I Am Sir Ask Alot
    Participant

    Great!

    That worked perfectly.

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

You must be logged in to reply to this topic.