In this article you will find out how to test LDAP Connection to your domain controllers. It is very similar to previous post about Test-PortConnection function.
In this example we will focus on making an LDAP connection using ADSI.
[adsi]"LDAP://DC01:636"
On the beginning of function we need to check if DC name provided as a parameter is valid:
Try{ $DCName = (Get-ADDomainController -Identity $DC).hostname } Catch{ $_.Exception.Message Continue }
Usage:
Test-LDAPConnection -DCs DC01 Test-LDAPConnection -DCs DC01 -Port 389 Test-LDAPConnection -DCs DC01,DC02 Test-LDAPConnection -DCs (GC "C:\temp\servers.txt") Test-LDAPConnection -DCs (GC "C:\temp\servers.txt") -Port 389 Test-LDAPConnection -DCs (GC "C:\temp\servers.txt") -Port 389 | Out-GridView -Title "Results" Test-LDAPConnection -DCs (GC "C:\temp\servers.txt") -Port 389 | Format-Table
Final script:
Function Test-LDAPConnection { [CmdletBinding()] # Parameters used in this function Param ( [Parameter(Position=0, Mandatory = $True, HelpMessage="Provide domain controllers names, example DC01", ValueFromPipeline = $true)] $DCs, [Parameter(Position=1, Mandatory = $False, HelpMessage="Provide port number for LDAP", ValueFromPipeline = $true)] $Port = "636" ) $ErrorActionPreference = "Stop" $Results = @() Try{ Import-Module ActiveDirectory -ErrorAction Stop } Catch{ $_.Exception.Message Break } ForEach($DC in $DCs){ $DC =$DC.trim() Write-Verbose "Processing $DC" Try{ $DCName = (Get-ADDomainController -Identity $DC).hostname } Catch{ $_.Exception.Message Continue } If($DCName -ne $Null){ Try{ $Connection = [adsi]"LDAP://$($DCName):$Port" } Catch{ $ExcMessage = $_.Exception.Message throw "Error: Failed to make LDAP connection. Exception: $ExcMessage" } If ($Connection.Path) { $Object = New-Object PSObject -Property ([ordered]@{ DC = $DC Port = $Port Path = $Connection.Path }) $Results += $Object } } } If($Results){ Return $Results } }
I’m finding that no exception is returned if you specify a bad port. You just get nothing returned. A success returns DC, Port, and Path as you know. Did you get exceptions in your testing?
I was just asking about this in PowerShell Slack channel. So the key is to close the connection it seems. If you add $Connection.Close() after line 254 then it properly throws an exception for bad ports.
Line 254??? I only see 60 lines in this script.