Adding User Accounts into a Group

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.

 

 $groupmember = Get-ADGroupMember groupname | Get-AdUser

foreach ($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.SamAccountName

Write-Output addtogroup

}
} 

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

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.

Thanks all I ended going with

foreach ($member in $groupmember)
{
$getuser = Get-ADPrincipalGroupMembership -Identity $member.SamAccountName | Where-Object {$_.name -eq 'groupname2' }
if($null -eq $getuser)
{

Add-ADGroupMember -Identity groupname2 -Members $member.SamAccountName

Write-Output addtogroup

}
}