Author Posts

March 9, 2015 at 11:01 am

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

March 9, 2015 at 1:44 pm

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.'
}

March 9, 2015 at 2:23 pm

Great!

That worked perfectly.

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