Home > Back-end >  LDAP how to display memberOf as a list of group names
LDAP how to display memberOf as a list of group names

Time:10-27

I have a question regarding reading LDAP base from data.json file in powershell. I would like the memberOf field to print only the group name like groupname itself, not the entire ldap path like CN=groupname,OU=Groups,DC=domain,DC=local.

My code:

cls 
$data = Get-Content C:\data.json  | ConvertFrom-Json

$entries = $data.entries
$users = $entries.attributes

$i = 1
foreach ($user in $users){
   $sAMAccountName = $user.sAMAccountName
   $memberOf = $user.memberOf
   echo $i
   echo $sAMAccountName
   echo $memberOf
   echo "-----------------------"
   $i  
}
$i = $null

Output:

1
batman
CN=Gotham,OU=Groups,OU=UNIVERSUM,DC=universum,DC=local
CN=DC-comics,OU=Groups,OU=UNIVERSUM,DC=universum,DC=local
CN=Justice-League,OU=Groups,OU=UNIVERSUM,DC=universum,DC=local
-----------------------
2
superman
CN=Metropolis,OU=Groups,OU=UNIVERSUM,DC=universum,DC=local
CN=DC-comics,OU=Groups,OU=UNIVERSUM,DC=universum,DC=local
CN=Justice-League,OU=Groups,OU=UNIVERSUM,DC=universum,DC=local
-----------------------
3
ironman
CN=New-York,OU=Groups,OU=UNIVERSUM,DC=universum,DC=local
CN=Marvel,OU=Groups,OU=UNIVERSUM,DC=universum,DC=local
CN=Avengers,OU=Groups,OU=UNIVERSUM,DC=universum,DC=local
-----------------------

I would like to get:

1
batman
Gotham
DC-comics
Justice-League
-----------------------
2
superman
Metropolis
DC-comics
Justice-League
-----------------------
3
ironman
New-York
Marvel
Avengers
-----------------------

CodePudding user response:

should do the trick:

$memberOf = ($user.memberOf -split ',')[0] -replace 'cn='

example:

("CN=Gotham,OU=Groups,OU=UNIVERSUM,DC=universum,DC=local"  -split ',')[0] -replace 'cn='

#Output:
Gotham

But as $user.memberOf is probably an array, you can do:

$memberOf = $user.memberOf | %{($_ -split ',')[0] -replace 'cn='}
$memberOf | %{
    write-host $_
}

Or with only replace:

$memberOf = $user.memberOf | %{$_ -replace 'cn=|,.*'}
$memberOf | %{
    write-host $_
}
  • Related