powershell 如何将LDAP memberOf显示为组名列表

toe95027  于 2023-02-12  发布在  Shell
关注(0)|答案(1)|浏览(127)

我有一个关于在powershell中从data.json文件读取LDAP库的问题。我希望memberOf字段只打印组名,如groupname本身,而不是整个LDAP路径,如CN=groupname,OU=Groups,DC=domain,DC=local
我的代码:

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

输出:

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
-----------------------

我想得到:

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

4dc9hkyq1#

应该可以做到

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

example:

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

#Output:
Gotham

但由于$user.memberOf可能是一个数组,因此您可以执行以下操作:

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

或仅替换:

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

相关问题