To the statement left by another member. If you don't run this from a Domain Controller you will need to either provide a static entry by replacing $domainController or you can add another , followed by $DomainController and pass that info.
To add a user to a group
Function AddUserToGroup($Group, $User, $DomainController)
{
if(!(Get-ADGroupMember -Identity $group | ?{$_.name -eq $User}))
{
Add-ADGroupMember -Identity $group -Members $User -Server $DomainController
}
else
{
return "The user: $User is already in the $group"
}
}
To remove a user you can do the same thing.
Function RemoveUserFromGroup($Group, $User, $DomainController)
{
if((Get-ADGroupMember -Identity $group | ?{$_.name -eq $User}))
{
Remove-ADGroupMember -Identity $group -Members $User -Server $DomainController
}
else
{
return "The user: $User is not a member of $group"
}
}
Now to use this you can do this...
$Users = Get-Aduser -Filter *
Foreach($user in $users)
{
AddUserToGroup "SomeGroup" $user.name "ServerName"
}
or
It would be best to have a disabled users OU or something where this can take place or if you switch OU's such as site or group
$Users = Get-Aduser -Filter *
Foreach($user in $users)
{
RemoveUserToGroup "SomeGroup" $user.name "ServerName"
}