I have a list of Users and a list of AD Groups. I would like to know, if any of the users are a member of those groups.
I have got this code:
$users = Get-Content C:\test\testusers.csv
$groups = Get-Contect C:\test\testgroups.csv
foreach ($user in $users) {
foreach ($group in $groups) {
$members = Get-ADGroupMember -Identity $group -Recursive |
Select -ExpandProperty SamAccountName
if ($members -contains $user) {
Write-Host "Match Found $group"
}
}
}
I have run this against a test of 4 users and 3 ad groups, whilst this gives me what I need. I get the output:
My understanding is that this is scanning each user against all groups, then the next user against all groups. Whilst this worked for my test batch in small numbers, I need to scan 2000 users against 1100 groups.
I take it this is because I am scanning the users against groups? and need to scan groups for users?
Is there a way I can put a line of code that says, if found move to next group?
Is there away i can put a line of code that says, if found move to next group?
Yes, you can use the break
key word, to break a foreach
loop.
However, I suggest to solve your requirement diffently.
I just need to know if ANY user matches a Group, if a match exists output Match found and group name.
More efficient then breaking after the first match, is to always query a group once. There are different options. One option would be to use Compare-Object
to find names that are member of a group and part of your input CSV, which is exactly what you call a match.
$users = Get-Content C:\test\testusers.csv
$groups = Get-Content C:\test\testgroups.csv
foreach ($group in $groups) {
$members = Get-ADGroupMember -Identity $group -Recursive
if (Compare-Object -ReferenceObject $members.SamAccountName -DifferenceObject $users -ExcludeDifferent -IncludeEqual) {
$group
}
}
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.