Reputation: 821
$GetGroupsFromUser = Get-ADPrincipalGroupMembership $WPFnamelookupbox.Text |
Where-Object { $_.Name -like 'G1*' }
$Groups = Get-ADGroup -Filter {Name -like "G1*"}
foreach ($G in $Groups) {
if ($GetGroupsFromUser -contains $G) {
} else {
$WPFgroups.Items.Add($G.SamAccountName)
}
}
My goal is I want to only show groups that the user is not a member of.
So I made some progress going with the -contains
operator. In order for -contains
to work, I need to first create an array, correct?
Upvotes: 1
Views: 247
Reputation: 46710
-contains
functions best when you are trying to find a match of an element in an array.
If you are just looking for the groups that matches a filter that a user does not already have we can use -notcontains
inside a where clause as well for this.
$groupFilter = "G*"
$user = "user_bagel"
$allFilteredGroups = Get-ADGroup -Filter "name -like '$groupFilter'" | Select-Object -ExpandProperty name
$userFilteredGroups = Get-ADPrincipalGroupMembership $user | Where-object{$_.name -like $groupFilter} | Select-Object -ExpandProperty name
$allFilteredGroups | Where-Object{$userFilteredGroups -notcontains $_}
You don't need to expand the groups names as I have done. You will get similar results either way. Since you only wanted to know the names it seemed silly to keep the complete group object. In theory it will also perform faster this way. Setting up variables like $groupFilter
makes it easier to make changes to your script down the line.
Upvotes: 1
Reputation: 10044
You could use Compare-Object
:
$GetGroupsFromUser = Get-ADPrincipalGroupMembership $WPFnamelookupbox.Text | Where-Object {$_.name -like 'G1*' }
$Groups = Get-ADGroup -Filter "name -like 'G1*'"
Compare-Object $Groups $GetGroupsFromUser | Where-Object {$_.SideIndicator -eq "<="}
Upvotes: 2