How to test LDAP connectivity in Powershell

Table of Contents

Case #

You need to test connectivity to an LDAP directory, for example Active Directory, by using Powershell. This KB article provides guidance on how to test LDAP connectivity in Powershell.

Solution #

To test LDAP connectivity in Powershell, follow the steps below.

  • Open PowerShell: Launch the PowerShell console by typing “PowerShell” in the Windows search bar and selecting “Windows PowerShell” or “Windows PowerShell (x86)”.
How to test LDAP connectivity in Powershell
  • Import the Active Directory module: In PowerShell, you need to import the Active Directory module to access the necessary cmdlets for testing LDAP connections. Enter the following command:
Import-Module ActiveDirectory
  • Define LDAP connection parameters: Specify the LDAP connection parameters required for testing. You’ll need the LDAP server address (hostname or IP address) and the port number (default is 389 for LDAP or 636 for LDAPS). Set the values for the variables $ldapServer and $ldapPort. You will need to adjust the parameters below to your environment and LDAP server setup.
$ldapServer = "<LDAP server address>"
$ldapPort = <LDAP port number>
  • Create LDAP connection object: Use the New-Object cmdlet to create an LDAP connection object. Enter the following command:
$ldapConnection = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$ldapServer:$ldapPort")
  • Test the LDAP connection: Use the Try and Catch statements to test the LDAP connection and handle any errors that occur. Enter the following code:
try {
    Write-Host "LDAP connection successful!"
} catch {
    Write-Host "LDAP connection failed. Error: $($_.Exception.Message)"
  • Execute the script: Run the script by pressing Enter. PowerShell will attempt to establish the LDAP connection using the provided parameters.
  • Interpret the result: The script will display the result of the LDAP connection test. If the connection is successful, you’ll see the message “LDAP connection successful!” in the console. If the connection fails, you’ll see an error message indicating the reason for the failure.

Powered by BetterDocs