问题
So I have the following script but it lists the full name of the AD group. (e.g. CN=GroupName,OU=OUName,DC=DomainName,DC=com
) How do I specify only the group's name, so that it lists only the name itself. The part after CN=
. I tried $group.Name
but no such luck.
Import-Module ActiveDirectory
$userlist = Get-Content "C:\Scripts\US_User_List.txt"
foreach ($username in $userlist) {
$grplist = (Get-ADUser $username –Properties MemberOf | Select-Object MemberOf).MemberOf
foreach ($group in $grplist) {
write-host $group
}
}
Also as a second question is there some way to filter based on what the group name starts with?
回答1:
You can look it up with Get-ADGroup
Import-Module ActiveDirectory
$userlist = Get-Content "C:\Scripts\US_User_List.txt"
foreach ($username in $userlist) {
$grplist = (Get-ADUser $username –Properties MemberOf).MemberOf
foreach ($group in $grplist) {
(Get-ADGroup $group).name
}
}
For the second part, you can use a Where-Object
/?
filter.
$grplist = (Get-ADUser $username –Properties MemberOf).MemberOf | ? {$_ -like "CN=StartsWithExample*"}
回答2:
Here's one way:
foreach ( $name in $names ) {
Get-ADUser $name -Properties memberOf |
Select-Object -ExpandProperty memberOf |
Get-ADPathname -Format Leaf -ValuesOnly |
Where-Object { ($_ -like "this*") -or ($_ -like "that*") } |
Sort-Object |
ForEach-Object {
[PSCustomObject] @{
"Name" = $name
"memberOf" = $_
}
}
}
You can adjust the filter in the Where-Object
scriptblock how you want it.
You can get the Get-ADPathname.ps1 script from here:
Windows IT Pro - Use PowerShell to Handle Active Directory Paths
A note on the Where-Object
filter - if you want to say "groups whose names do not start with this or that", you would write it this way:
Where-Object { -not (($_ -like "this*") -or ($_ -like "that*")) }
回答3:
There is one simple way : Get-ADPrincipalGroupMembership -Identity blabla | Select-Object Name
Get-ADPrincipalGroupMembership outputs the group objects a user is a member of and it comes with the default AD module.
来源:https://stackoverflow.com/questions/43123279/how-to-display-just-the-group-name-of-groups-user-is-member-of-in-powershell