Powershell脚本列出不属于两个组的用户

时间:2015-11-03 09:02:05

标签: powershell

我们的环境中有两个小组'承包商'和'员工' ,我需要编写一个脚本,列出不属于这两个组的所有用户,有人可以帮助我。

$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 个答案:

答案 0 :(得分:1)

$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"
   }
}

答案 1 :(得分:0)

我纠正了你的剧本,试试这个:

$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 
        }
 }