PowerShell: Test LDAPS Connection

Function testLdap {
    [CmdletBinding()]
    Param(
        [Parameter(Position=0,ValueFromPipeline=$true)]$dcs=$($ENV:LOGONSERVER -replace '\\',''),
        [Parameter(Position=1,ValueFromPipeline=$true)]$port='636'
    ) 

    $ErrorActionPreference = "Stop"
    $results = @()
    try{
        Import-Module ActiveDirectory
    }catch{
        write-warning "Active Directory module is not available on $env:computername."
        break
    }
    ForEach($dc in $dcs){
        Try{
            $validatedDc = (Get-ADDomainController -Identity $dc).hostname
        }Catch{
            write-warning $_
            Continue
        }

        If($Null -ne $validatedDc){  
            Try{
                $ldaps = [adsi]"LDAP://$($validatedDc):$port"
                $ldapPath=$ldaps.Path
                If ($ldapPath){
                    $result=New-Object PSObject -Property ([ordered]@{ 
                        DC=$dc
                        Port=$port
                        Path=$ldapPath
                        Success=$true
                    })
                    $results+=$result
                }
            }Catch{
                write-warning $_
                continue
            }        
        }
    }

    If($results){
        return $Results
    }else{
        write-host "No LDAP Connection success for $dcs"
    }
}

testLdap

Leave a Reply

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