網路上查到的PowerShell 讀取 LDAP 資訊,幾乎清一色都是讀取 Active Directory....
很少講到如何讀取 Linux LDAP Server
找了好久,終於找到 C# 讀取 LDAP 的資訊,改成 PowerShell
Clear-Host
$LDAPDirectoryService = '192.168.1.101:389'
$DomainDN = 'dc=mail,dc=company,dc=com'
# 讀取所有使用者
$LDAPFilter = '(&(objectClass=*)(uid=*))'
# 讀取指定使用者
#$LDAPFilter = '(&(objectClass=*)(uid=admin))'
$null = [System.Reflection.Assembly]::LoadWithPartialName('System.DirectoryServices.Protocols')
$null = [System.Reflection.Assembly]::LoadWithPartialName('System.Net')
$LDAPServer = New-Object System.DirectoryServices.Protocols.LdapConnection $LDAPDirectoryService
$LDAPServer.AuthType = [System.DirectoryServices.Protocols.AuthType]::Anonymous
$LDAPServer.SessionOptions.ProtocolVersion = 3
$LDAPServer.SessionOptions.SecureSocketLayer =$false
$Scope = [System.DirectoryServices.Protocols.SearchScope]::Subtree
# 讀取使用者所有屬性
#$AttributeList = @('*')
# 讀取指定屬性
$AttributeList = @('uidnumber')
$SearchRequest = New-Object System.DirectoryServices.Protocols.SearchRequest -ArgumentList $DomainDN,$LDAPFilter,$Scope,$AttributeList
$objs = $LDAPServer.SendRequest($SearchRequest)
# 抓多個使用者
ForEach($user in $objs.Entries){
# 拆解 uidnumber 屬性
$chars = $user.Attributes.uidnumber -split " "
$uidnumber = ""
$chars | ForEach{
# 將字串轉成數值,再轉成字元,然後將字元累加,串成字串
$uidnumber += [char][int]$_
}
$fields = $user.DistinguishedName -split ","
$UserAccount = $fields[0] -replace "uid="
# 格式化輸出帳號、使用者代號
If($UserAccount.Length -le 3){
"{0}`t`t`t`t{1}" -f $UserAccount, $uidnumber
}Elseif($UserAccount.Length -ge 11){
"{0}`t{1}" -f $UserAccount, $uidnumber
}Elseif($UserAccount.Length -ge 8){
"{0}`t`t{1}" -f $UserAccount, $uidnumber
}Else{
"{0}`t`t`t{1}" -f $UserAccount, $uidnumber
}
}
0 意見:
張貼留言