I have a couple powershell scripts that do parts of what I need separately. But don't know how to combine into one script. I want to limit the result list to check ONLY the list of users I provide.
So I want to know -- Is User1 in both Group1 AND Group2? Is User2 in both Group1 and Group2? Is User3 in both Group1 and Group3? etc..
Here are my separate scripts. I can also run the first once, then get a new list, and run it against group two. But would like to have one script if possible.
First script checks list and returns list included in group using a Get-Content command and ForEach.
$users = Get-Content C:\temp\user_list.txt
$group = "group1"
$members = Get-ADGroupMember -Identity $group -Recursive | Select -ExpandProperty samaccountname
ForEach ($user in $users) {
If ($members -contains $user) {
Write-Host "$user"
}
}
Second gets list of members from one Group1, then compares each user to Group2, returning positives.
#checks two specified groups against each other and returns who is in both lists
# Get the members of Group1
$group1 = get-adgroupmember "group1";
# Get the members of Group2
$group2 = get-adgroupmember "group2";
# Loop through each user in Group1
foreach ($group1user in $group1){
# For each user in Group1, loop through every user in Group2 looking for a match
foreach ($group2user in $group2){
# If a match is found
if ($group1user.samaccountname -eq $group2user.samaccountname) {
write-host $group1user.samaccountname;
}
}
}
CodePudding user response:
I'm making some assumptions here that there's always a group1/group2 and that user_list contains a list of user samaccountnames.
Instead of nested foreach loops based on the groups in your second code block, you might consider storing the group membership lists in variables like you did in your first code block:
$group1Members = Get-ADGroupMember -Identity "group1" -Recursive | Select -ExpandProperty samaccountname
$group2Members = Get-ADGroupMember -Identity "group2" -Recursive | Select -ExpandProperty samaccountname
Then you could loop through your desired list of users once, leveraging the Contains method, like so:
foreach($user in $users) {
if($group1Members.contains($user) -and $group2Members.contains($user)) {
# the user is in both groups
Write-Output $user
}
}
NOTE: There is a caveat - this assumes the capitalization of a user's samAccountName is an exact match. While string comparison is case-insensitive by default in PowerShell, when using Contains, this is not the case
One unrelated tip - you'll notice I used Write-Output - this is generally preferred to Write-Host as it can be captured to a variable or outputted to a file, etc, whereas Write-Host can't.