I want to return the group names in a semicolon delimited list for each AD user in an array. Here is what I have so far:
$ADuser = Get-ADUser -filter * -Properties * | ? {$_.employeeNumber -eq " 9408" -or $_.employeeNumber -eq "3816"} | Select-Object Name,SamAccountName,UserPrincipalName,DisplayName,GivenName,Surname,description,mail,Enabled,HomeDirectory,distinguishedname,MemberOf
foreach($user in $ADuser)
{
$Groups = forEach ($group in $ADuser.memberOf)
{
(Get-ADGroup $group).name
}
$groupStr = $Groups -join ";"
$ADuser = $ADuser | Select-Object Name,SamAccountName,UserPrincipalName,DisplayName,GivenName,surname,description,mail,Enabled,HomeDirectory,distinguishedname,@{n='Groups';e={$groupStr}}
}
This code works fine when $ADuser
contains a single user. When $ADuser
contains more than one user, I get the following error each time it tries to set Groups
:
Get-ADGroup : Cannot validate argument on parameter 'Identity'. The argument is null. Provide a valid value for the argument, and then try running the command again.
At line:8 char:22
+ (Get-ADGroup $group).name
+ ~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-ADGroup],
ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.GetADGroup
I expect the output to be like this for each $ADuser
:
Name : John.Doe
SamAccountName : John.Doe
UserPrincipalName : John.Doe@mydomain.com
DisplayName : John Doe
GivenName : John
Surname : Doe
description : Joe is a person
mail : John.Doe@mydomain.com
Enabled : True
HomeDirectory : \\fileserver\homefolders\John.Doe
distinguishedname : CN=John.Doe,OU=People,OU=my,DC=domain
Groups : Group1;Group2;Group3;Group4