I need to get specific users from specific Groups in Active Directory.
So far I have this:
$Groupnames = get-adgroup -Filter "name -like '$Groupfilter'" -Properties * -SearchBase $Grouppath |
Select-Object Name, @{
Name='Username';
Expression={
Get-ADGroupMember -identity $($_.Name) -Recursive |
Get-ADUser -Property SamAccountName |
Select -ExpandProperty SamAccountName
}
}
This works to get the Groups with their names. Now I want to get all users from these groups. what works but the formating is completly off. I want this:
Name Username
---- --------
Group1 user1adm
Group2 {user1adm, user1, user2, user2adm...}
Group3 {user1adm, user3, user2adm, user6...}
But I get this:
{user1adm, user1, user2, user2adm...}
With that formatting I can't see all users.
My goal at the end is also to exclude users who end with adm
, but I don't know how to do that.
Can you help me?
Get-ADGroupMember can return objects of type 'user', 'group' or 'computer', so piping the returned objects straight through to Get-ADUser
could get you into trouble if one of the objects is not a user.
Having said that, the objects returned from Get-ADGroupMember
already contain the SamAccountName property you are after, so you can eliminate Get-ADUser from the code.
$Groupnames = Get-ADGroup -Filter "name -like '$Groupfilter'" -SearchBase $Grouppath |
Select-Object Name,
@{Name = 'Username'; Expression = {
($_ | Get-ADGroupMember -Recursive |
Select-Object -ExpandProperty SamAccountName |
Where-Object { $_ -notmatch 'adm$' }
) -join ', '
}
}
# output the result on screen
$Groupnames | Format-Table -AutoSize
# output to CSV file
$Groupnames | Export-Csv -Path 'Path\To\The\GroupMembers.csv' -NoTypeInformation
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.