Search LDAP with Powershell

You can serach an OpenLDAP Server with Powershell. Here is a sample script.

# .\ldap.ps1 -UID abc

You can also use wildcard characters.

.\ldap.ps1 -UID abc*
param (
[String]$UID=""
)

$hostname = 'some.ldap.net:636'
$username = 'uid=abc,ou=People,o=ldap.net'
# Change Path to the Password File. In the password file must be the encrypted password, not clear text
$password = Get-Content "D:\Temp\Password.txt" | ConvertTo-SecureString

# Create Binding
$Null = [System.Reflection.Assembly]::LoadWithPartialName("System.DirectoryServices.Protocols")
#Connects to LDAP
$LDAPConnect = New-Object System.DirectoryServices.Protocols.LdapConnection "$HostName"

#Set session options (SSL + LDAP V3)
$LDAPConnect.SessionOptions.SecureSocketLayer = $true
$LDAPConnect.SessionOptions.ProtocolVersion = 3

# Pick Authentication type:
# Anonymous, Basic, Digest, DPA (Distributed Password Authentication),
# External, Kerberos, Msn, Negotiate, Ntlm, Sicily
$LDAPConnect.AuthType = [System.DirectoryServices.Protocols.AuthType]::Basic

# Gets username and password.
$credentials = new-object "System.Net.NetworkCredential" -ArgumentList $username,$password
#$credentials = new-object "System.Net.NetworkCredential" -ArgumentList $UserName,(Read-Host "Password" -AsSecureString)
# Bind with the network credentials. Depending on the type of server,
# the username will take different forms.
Try {
$ErrorActionPreference = 'Stop'
$LDAPConnect.Bind($credentials)
$ErrorActionPreference = 'Continue'
}
Catch {
Throw "Error binding to ldap  - $($_.Exception.Message)"
}

if (-not ([string]::IsNullOrEmpty($UID))) {
    $basedn = "ou=People,o=fhv.at"
    $scope = [System.DirectoryServices.Protocols.SearchScope]::Subtree
    #Null returns all available attributes
    $attrlist = $null
    $filter = "(uid="+$UID+")"

    $ModelQuery = New-Object System.DirectoryServices.Protocols.SearchRequest -ArgumentList $basedn,$filter,$scope,$attrlist

    #$ModelRequest is a System.DirectoryServices.Protocols.SearchResponse
    Try {
    $ErrorActionPreference = 'Stop'
    $Result = $LDAPConnect.SendRequest($ModelQuery) 
    $ErrorActionPreference = 'Continue'
    }
    Catch {
    Throw "Problem looking up model account - $($_.Exception.Message)"
    }

    # Create the Result Hash Array
    $ResultsHashArray = @{}
    $Index = 0

    foreach ($item in $Result.Entries) 
    {
        # Each Element which i want to output will be added to the Hash Array
        # The $Key Letter A, B, C, ... is for the correct sorting at the end of the script
        $Key = "A - UID"+$Index
        # Replace each attribute for your need (for example uid, ...)
        $Value = $item.attributes['uid'].GetValues('string')
        $ResultsHashArray.add($Key, $Value)

        $Key = "B - DisplayName"+$Index
        $Value = $item.attributes['displayName'].GetValues('string')
        $ResultsHashArray.add($Key, $Value)

        $Key = "D - Telephone"+$Index
        # If no Telephone Number is set fill with "---"
        Try {
            $Value = $item.attributes['telephoneNumber'].GetValues('string')
        } Catch {
            $Value = "---"
        } Finally {
            $ResultsHashArray.add($Key, $Value)
        }

        $Key = "C - Office"+$Index
        Try {
            $Value = $item.attributes['physicalDeliveryOfficeName'].GetValues('string')
        } Catch {
            $Value = "---"
        } Finally {
            $ResultsHashArray.add($Key, $Value)
        }

        $Key = "E - Mail"+$Index
        $Value = $item.attributes['mail'].GetValues('string')
        $ResultsHashArray.add($Key, $Value)

        $Key = "F - Password"+$Index
        $Value = $item.attributes['Password'].GetValues('string')
        $ResultsHashArray.add($Key, $Value)

        $Index = $Index + 1
    }

    Write-Host ""
    $SizeHashArray =  $ResultsHashArray.Count
    # We have six values (A, B, C, D, E, F) for each result. So we must divide six for the number of results.
    $EntriesHashArray = $SizeHashArray / 6
    $i = 0

    for ($i; $i -le $EntriesHashArray; $i++) {
        $ResultsHashArray.GetEnumerator() | Sort-Object -Property Name | ForEach-Object{

            if ($_.Key.ToString().Trim() -like "*$i*") {
                if ($_.Key.ToString().Trim() -like "*UID*") {
                    Write-Host "UID:             "$_.Value -ForegroundColor DarkCyan      
                }    
        
                if ($_.Key.ToString().Trim() -like "*DisplayName*") {
                    Write-Host "NAME:            "$_.Value -ForegroundColor DarkCyan      
                }    
        
                if ($_.Key.ToString().Trim() -like "*Office*") {
                    Write-Host "OFFICE:          "$_.Value -ForegroundColor DarkCyan
                }    
        
                if ($_.Key.ToString().Trim() -like "*Telephone*") {
                    Write-Host "TELEPHONE:       "$_.Value -ForegroundColor DarkCyan
                }

                if ($_.Key.ToString().Trim() -like "*Mail*") {
                    Write-Host "MAIL:            "$_.Value -ForegroundColor DarkCyan
                }
     
                if ($_.Key.ToString().Trim() -like "*Password*") {
                    Write-Host "PASSWORD:        "$_.Value -ForegroundColor DarkCyan
                }
            }
        }
        if ($i -lt $EntriesHashArray-1) {
            Write-Host "----------------------------------------------"
        }
         
    }

    Write-Host ""

}

 

 

Leave a Reply

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