Reputation: 27
I am new to powershell and wanted to learn how to get the groups belonging to a user as well as other user object properties in the format below (repeating the user and email for each group):
username user_email user_groups
user1 [email protected] group1
user1 [email protected] group2
user1 [email protected] group3
user2 [email protected] group1
user2 [email protected] group2
...
I understand that this gets the groups of a user but unsure of how to include other user objects and have it repeated in the above format:
Get-ADPrincipalGroupMembership username | select name
Upvotes: 0
Views: 565
Reputation: 8868
No reason to overcomplicate it. I've added the Get-ADOU call in case you want to use the name of the group instead of the distinguished name.
$ouname = "Some OU"
$OU = Get-ADOrganizationalUnit -Filter "name -eq '$ouname'"
Get-ADUser -Filter * -SearchBase $OU -Properties mail | Foreach-Object {
Foreach($group in Get-ADPrincipalGroupMembership $_)
{
[PSCustomObject]@{
UserName = $_.samaccountname
User_Email = $_.mail
User_Group = $group.name
}
}
}
Upvotes: 1
Reputation: 801
You'll want to get your ADUser objects, expand their memberof property, iterate through those, and get the ad group of each.
$username = "PowerShellGuy"
$adUserObj = Get-ADUser -Filter "SamAccountName -eq '$username'" -properties memberof
$groups = $adUserObj.MemberOf | Get-ADgroup
You can one-line it like this
Get-ADUser -Filter "SamAccountName -eq 'PowerShellGuy'" -properties memberof | % memberof | Get-ADgroup
If you want custom formatting, you can build a custom psobject, or a custom class. I prefer the class method
Class CustomAdInfo
{
$UserName
$Email
$Group
}
If you want one group per, then you can do something like this
Class CustomAdInfo
{
$UserName
$Email
$Group
}
$listOfUsers = @("foo","bar")
$customObjects =
foreach($user in $listOfUsers)
{
$adUserObj = Get-ADUser -Filter "SamAccountName -eq '$user'" -properties memberof, emailaddress
$groups = $adUserObj.MemberOf | Get-ADgroup
foreach($group in $groups)
{
New-Object -TypeName CustomAdInfo -Property @{
UserName = $adUserObj.SamAccountName
Email = $adUserObj.EmailAddress
Group = $group
}
}
}
Upvotes: 1