简体   繁体   中英

Get-ADUser within a specific AD group

I'd like to get an AD user account via powershell within a specific group.

I will know the GivenName and Surname of the user I will be looking for, so Get-ADUser seems like a good function to use.

The issue is that we have a large number of users in the OU and I want to limit the scope of the search to one AD group and the groups under that one AD group. As far as I can tell, the SearchBase parameter of Get-ADUser will only work for OUs and not for groups.

I'd like to do this as efficiently as possible (ie not get all the users in the group and search within those users).

You could use Get-ADGroupMember for enumerating the members of a group, and use that as input for Get-ADUser :

Get-ADGroupMember 'groupname' |
  Get-ADUser -Properties EmailAddress |
  Where-Object { $_.Surname -eq 'foo' -and $_.GivenName -eq 'bar' } |
  Select-Object -Expand EmailAddress

If the group contains not only user objects you need to filter the members by class first:

Get-ADGroupMember 'groupname' |
  Where-Object { $_.objectClass -eq 'user' } |
  Get-ADUser -Properties EmailAddress |
  Where-Object { $_.Surname -eq 'foo' -and $_.GivenName -eq 'bar' } |
  Select-Object -Expand EmailAddress

For unrolling nested groups you need a recursive function:

function Unroll-Group($group) {
  Get-ADGroupMember $group | ForEach-Object {
    $userOrGroup = $_
    switch ($_.objectClass) {
      'group' { Unroll-Group $userOrGroup }
      'user'  { Get-ADUser $userOrGroup -Property EmailAddress }
    }
  }
}

Unroll-Group 'groupname' |
  Where-Object { $_.Surname -eq 'foo' -and $_.GivenName -eq 'bar' } |
  Select-Object -Expand EmailAddress

Note that this approach won't work for a user's primary 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM