PowerShell Script to Loop Over All Users in a Group

4

I'm running Windows 7 Professional.

I know how to get a list of all the users in a group:

$ou="User Groups"
$userADName="RRAS VPN SSL"
$userADPath="LDAP://proddc6.prod.root/CN="+$userADName+",OU="+$ou+",DC=prod,DC=root"
$user = [adsi] $userADPath
$user.Member

I tried iterating over that list, creating an [adsi] object for each:

$ou="User Groups"
$userADName="RRAS VPN SSL"
$userADPath="LDAP://proddc6.prod.root/CN="+$userADName+",OU="+$ou+",DC=prod,DC=root"
$user = [adsi] $userADPath
$user.Member| ForEach-Object {[adsi] ("ldap://proddc6.prod.root/" + $_)}

I was thinking of looping over the list of objects and fetching the email address and full name, then running some commands using that information. Instead, this produces the error:

The following exception occurred while retrieving member "PSComputerName": "Unknown error (0x80005000)"
    + CategoryInfo          : NotSpecified: (:) [format-default], ExtendedTypeSystemException
    + FullyQualifiedErrorId : CatchFromBaseGetMember,Microsoft.PowerShell.Commands.FormatDefaultCommand

How can I iterate over the list of users in a group, processing the email address and full name for each user?

active-directory
powershell
asked on Server Fault Oct 14, 2011 by John Saunders

1 Answer

1

You get this error because the LDAP path that you are sending to the loop is not right. You are pipeing $user.Member to the ForEach-Object, it sends all users and not one bye one.

So you are sending something like:

ldap://proddc6.prod.root/CN=User1,CN=Users,DC=prod,DC=root CN=User2,CN=Users,DC=prod,DC=root

I created this script based on yours, it do what you need: interate over the members of a group. Do what you want with the object $useradsi in the loop.

$ou="User Groups"
$userADName="RRAS VPN SSL"
$objADSI = [adsi]””
$domain = $objADSI.distinguishedname
$userADPath="LDAP://CN="+$userADName+",OU="+$ou+",$domain"
$user = [adsi] $userADPath

foreach($child in $user.member) {
$useradsi = [adsi] "LDAP://$child"
}
answered on Server Fault Oct 16, 2011 by Ricardo Polo Jaramillo • edited Oct 16, 2011 by Ricardo Polo Jaramillo

User contributions licensed under CC BY-SA 3.0