Reputation: 847
I have list of users and i am trying to see if they belong to specific Azure AD group. At the end i want the result to be something like this.
EmailAddress Group1 Group2
[email protected] Y N
[email protected] N Y
[email protected] Y Y
Here is what i got so far:
#authenticate
Connect-MsolService
$users = "[email protected]", "[email protected]", "[email protected]"
$groupLists = "Group1", "Group2"
#create the object with Email, and group name as property name
$output = New-Object -TypeName psobject
$output | Add-Member -MemberType NoteProperty -Name Email -Value ""
$groupLists | ForEach-Object{
$output | Add-Member -MemberType NoteProperty -Name $_ -Value ""
}
#go through each group and user and update the output array
$userExistsInGroup;
foreach ($groupName in $groupLists) {
#get group info
$group = Get-Msolgroup -All | Where-Object {$_.DisplayName -eq $groupName}
#get all members of the group
$members = Get-MsolGroupMember -GroupObjectId $group.ObjectId | Select-Object -ExpandProperty EmailAddress
foreach ($user in $users) {
If ($members -contains $user) {
$userExistsInGroup; = "Y"
} Else {
$userExistsInGroup = "N"
}
# update Email and group property in $output object
......
}
}
Need help updating $output object so that i can display the result the way i want it on the top? since the same user might show up in different group during loop, if there is existing user in the object, then it will need to update property of the same user that matches with the group so that at the end each row output belongs to one user similar to what i have on the top.
Upvotes: 0
Views: 101
Reputation: 8868
To accommodate a dynamic list of groups, you can use this approach.
$userlist = "[email protected]", "[email protected]", "[email protected]"
$grouplist = "Managers","Directors","Information Technology"
$grouphash = @{}
foreach($group in $grouplist)
{
$grouphash[$group] = Get-MsolGroupMember -GroupObjectId (Get-Msolgroup | Where-Object {$_.DisplayName -eq $group}).objectid
}
foreach($user in $userlist)
{
$userhash = [ordered]@{
EmailAddress = $user
}
$grouplist | ForEach-Object {
$userhash.add($_,($user -in $grouphash[$_].emailaddress))
}
[PSCustomObject]$userhash
}
Each group name will be the property for that group containing true/false if the user is a member.
To collect all the output in a variable simply put $variable =
in front of the user foreach loop.
Here is what the output looks like in this example
Upvotes: 1