Last active
June 20, 2025 13:34
-
-
Save lewebsimple/98ad7a7e2c1e0634dfd480d4c72d94dc to your computer and use it in GitHub Desktop.
List LDAP users
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <# | |
| .SYNOPSIS | |
| Lists LDAP user accounts. | |
| .DESCRIPTION | |
| Connects to an LDAP server using credentials and searches for user objects. | |
| #> | |
| # Prompt for LDAP server and credentials | |
| $ldapServer = Read-Host "Enter LDAP server (e.g., ldap://your-ldap-server or dc01.domain.com)" | |
| $baseDN = Read-Host "Enter Base DN (e.g., dc=example,dc=com)" | |
| $cred = Get-Credential -Message "Enter LDAP credentials" | |
| # Build full LDAP path | |
| $ldapPath = "LDAP://$ldapServer/$baseDN" | |
| try { | |
| # Connect and bind to LDAP | |
| $entry = New-Object System.DirectoryServices.DirectoryEntry($ldapPath, $cred.UserName, $cred.GetNetworkCredential().Password) | |
| # Create DirectorySearcher | |
| $searcher = New-Object System.DirectoryServices.DirectorySearcher($entry) | |
| $searcher.Filter = "(&(objectCategory=person)(objectClass=user))" # Filter for user accounts | |
| $searcher.PageSize = 1000 # Enables paged results | |
| # Properties to return | |
| $searcher.PropertiesToLoad.Add("sAMAccountName") | Out-Null | |
| $searcher.PropertiesToLoad.Add("displayName") | Out-Null | |
| $searcher.PropertiesToLoad.Add("mail") | Out-Null | |
| # Perform the search | |
| $results = $searcher.FindAll() | |
| Write-Host "`nFound $($results.Count) user(s):`n" -ForegroundColor Cyan | |
| foreach ($result in $results) { | |
| $user = $result.Properties | |
| Write-Host "Username: $($user['sAMAccountName'][0])" | |
| Write-Host "Display Name: $($user['displayName'][0])" | |
| Write-Host "Email: $($user['mail'][0])" | |
| Write-Host "---------------------------" | |
| } | |
| } | |
| catch { | |
| Write-Host "`n❌ LDAP query failed:" -ForegroundColor Red | |
| Write-Host $_.Exception.Message -ForegroundColor Yellow | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment