1

I have a powershell script that I've written that gets all of the groups from an OU and stores them in a variable $groups. I want to be able to access the users of each group but seem to be having trouble. I've tried:

foreach($group in $groups){$get-ADUser $group}

Which gives me the following error:

You must provide a value expression on the right-hand side of the '-' operator.
At line:1 char:33
+ foreach($group in $groups){$get- <<<< ADUser $group}
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : ExpectedValueExpression

I am using Windows Server 2003 R2 on a windows 7 machine. I'm pretty new to this so any help is greatly appreciated.

  • The main problem with your script was that you put a $ in front of the get-ADUser command - $ is used for variables. Also, as mentioned in the answer, you wanted to be using Get-ADGroupMember instead of Get-ADUser. – ChadH360 Apr 24 '15 at 23:57
5

To retrieve only the members that are users, and not groups:

foreach($group in $groups)
{
  Get-ADGroupMember $group | Where-Object {$_.objectClass -eq "user"}
}

If you want users who are members of the groups indirectly (through nested group memberships), user the -Recursive switch parameter:

foreach($group in $groups)
{
  Get-ADGroupMember $group -Recursive | Where-Object {$_.objectClass -eq "user"}
}

You can then assign the output to a variable for further use, like so:

$AllGroupMembers = foreach($group in $groups)
{
  Get-ADGroupMember $group -Recursive | Where-Object {$_.objectClass -eq "user"}
}
4

Try this:

foreach ($group in $groups)
{
    Get-ADGroupMember $group | select Name
}

Get-ADUser is looking for an Active Directory User object, what you're essentially trying to do is use that cmdlet on an Active Directory Group object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.