Skip to content

Instantly share code, notes, and snippets.

@robderickson
Created October 17, 2024 12:13
Show Gist options
  • Save robderickson/174d509cb7b35c462d8720254be6bc5f to your computer and use it in GitHub Desktop.
Save robderickson/174d509cb7b35c462d8720254be6bc5f to your computer and use it in GitHub Desktop.
PowerShell function to bind to LDAP
# Works when connecting to AD from Ubuntu 22.04. May have a dependency on OpenLDAP (libldap-commnad, libldap)?
function Connect-Ldap {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$ComputerName,
[switch]$UseTLS,
[int]$Port,
[Parameter(Mandatory = $true)]
[PSCredential]$Credential
)
process {
$ComputerName = [System.Management.Automation.Language.CodeGeneration]::EscapeSingleQuotedStringContent("$($ComputerName)")
if ($UseTLS -and !$Port) {
$Port = 636
} elseif (!$Port) {
$Port = 389
}
$ldapDirectoryIdentifier = New-Object System.DirectoryServices.Protocols.LdapDirectoryIdentifier("$ComputerName", $Port)
$ldapConnection = New-Object System.DirectoryServices.Protocols.LdapConnection($ldapDirectoryIdentifier)
if ($UseTLS) {
$ldapConnection.SessionOptions.SecureSocketLayer = $true
}
$ldapConnection.SessionOptions.ProtocolVersion = 3
$ldapConnection.AuthType = [System.DirectoryServices.Protocols.AuthType]::Basic
try {
$ldapConnection.Bind($Credential)
$ldapConnection
} catch {
Write-Error $_.Exception.Message
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment