Author Posts

July 7, 2016 at 10:57 am

Hello Guys,

I am aiming to add multiple users to an AD group and seen to be running into an error.
______________________________________________________________________________________________
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null

$UserName = [Microsoft.VisualBasic.Interaction]::InputBox("Enter usernames (seperated by a coma)", "User", "$env:username")
$ADGroupName = [Microsoft.VisualBasic.Interaction]::InputBox("Enter name of AD Group", "ADGroup", "$env:ADGroup")

$Users = $UserName.Split(",").Trim()
ForEach ($user in $Users)
{
Add-ADGroupMember -Identity $ADGroupName -Members "$Users "
}
_________________________________________________________________________________

I am getting the following error:
Add-ADGroupMember : Cannot find an object with identity: ',longstaffd LAWS2 ' under: 'DC=user,DC=ad,DC=glasgow,DC=gov,DC=uk'.
At line:12 char:6
+ Add-ADGroupMember -Identity $ADGroupName -Members ",$Users "
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (,longstaffd LAWS2 :ADPrincipal) [Add-ADGroupMember], ADIdentityNotFoundException
+ FullyQualifiedErrorId : SetADGroupMember.ValidateMembersParameter,Microsoft.ActiveDirectory.Management.Commands.AddADGroupMember

Add-ADGroupMember : Cannot find an object with identity: ',longstaffd LAWS2 ' under: 'DC=user,DC=ad,DC=glasgow,DC=gov,DC=uk'.
At line:12 char:6
+ Add-ADGroupMember -Identity $ADGroupName -Members ",$Users "
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (,longstaffd LAWS2 :ADPrincipal) [Add-ADGroupMember], ADIdentityNotFoundException
+ FullyQualifiedErrorId : SetADGroupMember.ValidateMembersParameter,Microsoft.ActiveDirectory.Management.Commands.AddADGroupMember
_________________________________________________________________________________________________________________

I imagine the issue is that the script is not adding in the coma to separate the users, any ideas?

Thanks.

*** EDIT ***

Sorry guys i managed to suss the issue after all.

Changed Users to Username in the last line of the code.

( Not sure how to delete the post)
Thanks.

July 7, 2016 at 3:18 pm

You did catch the main issue, which was referencing $Users rather than $User. Just keep in mind you should add some basic error handling to your code as well:

...
foreach ($user in $Users) {
    try {
        Add-ADGroupMember -Identity $ADGroupName -Members $User -ErrorAction Stop
    }
    catch {
        #Friendly error message
        "Unable to add user {0} to group {1}. {2}" -f $user, $ADGroupName, $_
    }
}