Test LDAP Connection with PowerShell

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

Output:

LDAP Connection
LDAP Connection

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

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.