1
votes

There are two groups in our environment 'contractors' and 'employees' , I need to write a script that lists all users who are not part of both the groups, can some one help me with it.

$n = Get-ADGroupMember "Contractor" | Sort-Object |
     foreach {Get-ADUser $_.name | select name}
$group = "Employee" 

foreach ($u in $n) {
    $get = (Get-ADUser $u.Name -Properties * | Select-Object memberof) 

    if ($get.memberof -match $group) { 
        Write-Host $u.name " is ok. They're in both groups." 
    } else { 
        Write-Host $u.Name " is not a member" -ForegroundColor Red -BackgroundColor Yellow 
    }
}
2
Sure. Show us the code you have so far and explain what particular problem you ran into, and we'll help you improve from there.Ansgar Wiechers
I am not getting the correct output , attached the script I have triedBunny
Please edit your question. As you can see code tends to become unreadable in a comment. If you're not getting correct output you also need to provide sample input as well as actual and desired output.Ansgar Wiechers
Did you get any errors when you ran this code? If yes link post error codekekimian
The error I am getting is I am getting list of users that are part of either group(Contractor or Employee), I need an output of users who are not part of both the groupsBunny

2 Answers

1
votes
$AllUsers = Get-ADUser -Filter * -Properties memberof
foreach ($User in $AllUsers) {
   if (($User.memberof -match "Employee") -and ($User.memberof -match "Contractor")) {
       Write-Host -ForegroundColor Green "$($User.samaccountname) in both groups"
   } else {
       Write-Host -ForegroundColor Red "$($User.samaccountname) not in both groups"
   }
}
0
votes

I corrected your script, try this:

$n = get-adgroupmember "Contractor" | sort-object |foreach {get-aduser $_.SamAccountName} 
$group = "Employee" 
Foreach ($u in $n){ 
    $get = (get-aduser $u.SamAccountName -Properties * | Select-Object memberof)
        if ($get.memberof -match $group) { 
            Write-Host "$($u.name)  is ok. They're in both groups." } 
        Else { write-host $($u.name) " is not a member" -ForegroundColor Red -BackgroundColor Yellow 
        }
 }