【问题标题】:Powershell script to list users who are not part of two groups用于列出不属于两个组的用户的 Powershell 脚本
【发布时间】:2015-11-03 19:08:50
【问题描述】:

我们的环境中有两个组 'contractors' 和 'employees' ,我需要编写一个脚本来列出不属于这两个组的所有用户,有人可以帮助我吗?

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

【问题讨论】:

  • 当然。向我们展示您目前拥有的代码并解释您遇到的具体问题,我们将帮助您从那里改进。
  • 我没有得到正确的输出,附上我试过的脚本
  • 请编辑您的问题。如您所见,代码在注释中往往变得不可读。如果您没有得到正确的输出,您还需要提供示例输入以及实际和期望的输出。
  • 您在运行此代码时是否遇到任何错误?如果是链接发布错误代码
  • 我得到的错误是我正在获取属于任一组(承包商或员工)的用户列表,我需要不属于这两个组的用户的输出

标签: powershell


【解决方案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"
   }
}

【讨论】:

  • 这正在工作,谢谢,我会将其标记为已回答
  • 太好了,感谢马特的编辑 :)。如果您对答案满意,请标记。
  • 我怀疑逻辑已关闭,并且 OP 需要所有不在其中一个组中的用户。我怀疑用户需要在其中一个中,但不是两者兼而有之。无论哪种方式,OP 都忘记投票以给予信任,并标记已回答。
  • 我认为“我需要编写一个脚本,列出不属于这两个组的所有用户”,无论是在任何组中还是在其中一个组中。
【解决方案2】:

我更正了你的脚本,试试这个:

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

【讨论】:

  • 嗨,我仍然得到相同的输出,它列出了“承包商”组的用户
  • 员工应该是用户吗?
  • 不...它应该列出不属于“员工”和“承包商”的用户
  • 脚本的结果永远不可能是真的(不是“员工”和“承包商”的一部分),因为您的查询是基于您的“承包商”组的成员...,所以用户帐户您检查的默认情况下存在于“承包商”组中。
猜你喜欢
  • 1970-01-01
  • 2010-09-30
  • 1970-01-01
  • 2013-09-17
  • 2016-09-02
  • 1970-01-01
  • 2012-08-04
  • 2019-04-30
  • 2022-08-24
相关资源
最近更新 更多