Welcome › Forums › General PowerShell Q&A › Adding User Accounts into a Group
- This topic has 2 replies, 3 voices, and was last updated 4 months, 3 weeks ago by
Senior Moderator.
-
AuthorPosts
-
-
September 2, 2020 at 10:25 am #254033
What I am trying to achieve is to get a list of users from groupname and then if they are not in groupname2 add them into it, but nothing is happening. Any help would be mush appreciated.
PowerShell1234567891011121314$groupmember = Get-ADGroupMember groupname | Get-AdUserforeach ($member in $groupmember){$getuser = Get-ADPrincipalGroupMembership -Identity $member.SamAccountName | Select-Object name | Where-Object {$_.name -eq 'groupname2' }if($getuser -ne $()){Add-ADGroupMember -Identity groupname2 -Members $getuser.SamAccountNameWrite-Output addtogroup}}-
This topic was modified 4 months, 3 weeks ago by
blue_man51.
-
This topic was modified 4 months, 3 weeks ago by
blue_man51.
-
This topic was modified 4 months, 3 weeks ago by
kvprasoon. Reason: code formatting
-
This topic was modified 4 months, 3 weeks ago by
kvprasoon. Reason: correct post
-
This topic was modified 4 months, 3 weeks ago by
-
September 2, 2020 at 10:56 am #254081
might be easier to just change your initial groupmember query to include the property memberof. then your check becomes alot simpler, if ($member.memberof -like “*groupname*”) {do something}
then you don’t have to loop through adprinicpalgroupmembership and evaluate every group, should be faster as well
-
This reply was modified 4 months, 3 weeks ago by
David Schmidtberger.
-
This reply was modified 4 months, 3 weeks ago by
-
September 2, 2020 at 10:59 am #254087
You don’t need to use Select-Object here as all the objects are passed through the pipeline, Hence Where-Object has access to all the properties.
Hope with $getuser -ne $() you are trying to check if its null or not, the right way to do it is $null -ne $getuser
Try by making above modification to your script.
-
This reply was modified 4 months, 3 weeks ago by
kvprasoon. Reason: Post correction
-
This reply was modified 4 months, 3 weeks ago by
-
September 2, 2020 at 4:40 pm #254255
Thanks all I ended going with
PowerShell123456789101112foreach ($member in $groupmember){$getuser = Get-ADPrincipalGroupMembership -Identity $member.SamAccountName | Where-Object {$_.name -eq 'groupname2' }if($null -eq $getuser){Add-ADGroupMember -Identity groupname2 -Members $member.SamAccountNameWrite-Output addtogroup}}-
This reply was modified 4 months, 3 weeks ago by
grokkit. Reason: HTML parsing fix
-
This reply was modified 4 months, 3 weeks ago by
-
-
AuthorPosts
- The topic ‘Adding User Accounts into a Group’ is closed to new replies.