Add users from another domain to AD group - powershell

I need to add all users from one AD group to another AD group. Both groups are in the same domain, though the users are from another domain in the forest.
Domain "LPC": $Source_Group and $Destination_Group
Domain "forestx": Users
Here one example I wrote with the help of this Microsoft article:
$Source_Group = "CN=TestSrc,OU=xxx,OU=yyy,DC=lpc,DC=de"
$Destination_Group = "CN=TestDest,OU=xxx,OU=yyy,DC=lpc,DC=de"
$SourceUseres = Get-ADGroupMember -Identity $Source_Group
foreach ($Person in $SourceUseres) {
$User = Get-ADUser $Person -Server forestx-dc-1
Add-ADPrincipalGroupMembership -Server lpc-dc-1 $User -MemberOf $Destination_Group
}
Get-ADUser $Person -Server forestx-dc-1 seems to contain the right object if I write it to the comand line, but the reference seems not to work in the Add-ADPrincipalGroupMembership statement.

I found the answer myself using the Set-ADObject command:
$Source_Server = "x1"
$Source_Group = Get-ADGroup "xxx" -Server $Source_Server
$Destination_Server = "y1"
$Destination_Group = Get-ADGroup "yyy" -Server $Destination_Server
$SourceUseres = Get-ADGroupMember -Identity $Source_Group
foreach ($Person in $SourceUseres) {
Set-ADObject -Identity $Destination_Group -Add #{member=$Person.distinguishedName} -Server $Destination_Server
}

Related

How to compare users and users in an OU then add the users using Powershell

$Users = Get-ADGroupMember -Identity " Colorado Students" | Get-ADUser -properties SamAccountName
$OU = Get-ADUser -SearchBase ‘OU=Colorado,OU=Middle,OU=Student,OU=Colorado-Users,DC=Colorado,DC=9,DC=CO,DC=US’ -Filter * -Properties SamAccountName
$OU = $OU | Where SamAccountName -notlike $Users
Foreach ($user in $OU) {
Add-ADGroupMember -Identity ‘Colorado Students' -Members $_
}
I am using Powershell 5.0 I am struggling with finishing this one. I want to compare my users to all users in OU then if users are in OU then add.
I believe what you're looking for is to Add all users on the Colorado OU that are currently not members of the Colorado Students group. If that's the case, below code should work:
$groupName = 'Colorado Students'
$adGroup = Get-ADGroup $groupName
$OU = 'OU=someOU,OU=Of,OU=Some,DC=Domain,DC=xyz'
# Look for all users on the OU 'someOU' that are NOT
# MemberOf 'Colorado Students'
$hash = #{
SearchBase = $OU
LDAPFilter = "(!memberOf={0})" -f $adGroup.DistinguishedName
}
$users = Get-ADUser #hash
Add-ADGroupMember -Identity $adGroup -Members $users

Cannot search by Division attribute

I am wanting to create security group for filtering purposes, they do not exist yet and I am wanting to create them.
I would like to get all my AD user and select the value of the Division field.
With that field I'd like to add them to a group in an OU called "SafetyNet"
If the group that matches the name of their division exist - they would be added to that group. If not, the group would be created and then they would be added.
I imagine it would look something like this:
$users = get-aduser -filter "enabled -eq '$true' -and division -like '*'" -properties division
foreach ($user in $users) {
$group = get-adgroup $user.division
if ($group) {
$groupname = get-adgroup -Filter "name -like '$($user.division)'"
Add-ADGroupMember -Identity $groupname -members $user
}
else {
new-adgroup -name $user.division -SamAccountName $user.division -GroupCategory Security -GroupScope global -path "OU=TinyPulse, DC=smh, DC=org"
start-sleep -Seconds 5
Add-ADGroupMember -Identity $user.division -Members $user
}
}
It doesn't seem like division is a searchable attribute which make this difficult.

Get-ADuser : A referral was returned from the server

I'm getting the following error when I run my script:
Get-ADUser : A referral was returned from the server At line:25 char:70
+ ... -Identity $G.name -Recursive | Get-ADUser -Server $dom -Properties *
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ResourceUnavailable: (CN=User...,DC=org:ADUser) [Get-ADUser], ADReferral Exception
+ FullyQualifiedErrorId : ActiveDirectoryServer:****,Microsoft.ActiveDirectory.Management.Commands.GetADUser
This is my script:
$Domains = (Get-ADForest).Domains.ForEach{(Get-ADDomain $_).PDCEmulator}
$Users = #()
$Groups = #()
$list = Get-Content C:\temp\ADGroups.txt
ForEach ($dom in $Domains) {
Foreach ($o in $list) {
$ObjectClass = (Get-ADObject -server $dom -Filter {SamAccountName -eq $o}).ObjectClass
If ($ObjectClass -eq "User") {
$U = Get-ADUser -Properties * -Identity $o -Server $dom
$User = "" | Select FullUserName, LoginID, Description
$User.FullUserName = $U.DisplayName
$User.LoginID = $U.SamAccountName
$User.Description = $U.description
$Users += $User
} Else {
If ($ObjectClass -eq "Group") {
$G = Get-ADGroup -Properties * -Identity $o -Server $dom
$GM = Get-ADGroupMember -Server $dom -Identity $G.name -Recursive | Get-ADUser -Server $dom -Properties *
Foreach ($gmember in $GM) {
$Group = "" | Select GroupName, GroupDescription, GroupMemberName, GroupMemberLoginID, GroupMemberDesc
$Group.GroupName = $G.Name
$Group.GroupDescription = $G.Description
$Group.GroupMemberName = $gmember.Name
$Group.GroupMemberLoginID = $gmember.SamAccountName
$Group.GroupMemberDesc = $gmember.Description
$Groups += $Group
}
}
}
}
}
$Users | Export-Csv C:\temp\Users.csv -NoTypeInformation
$Groups | Export-Csv C:\temp\Groups.csv -NoTypeInformation
The purpose of my script is to pull users that belong in a group and export to a .csv file. It works for the most part, but it gives me an error for certain users. I think it could be because those users in the group belong in a different domain.
See the answers in this question. Answers there indicate you can retrieve the referral location in the exception and retry the Get-ADUser against the other server.
You might reconsider how you search for all these groups and users. Users are replicated throughout the forest. Global and Universal groups are too. So you could search the Global Catalog instead of iterating through one DC in every domain. Get-DomainController -GlobalCatalog and run your Get-AD* commands against that server's global catalog port, i.e. Get-ADUser -server $GCServerName:3268
However, bear in mind that the GC doesn't contain complete user and group properties, and the properties it does return are subject to replication delays.
Whether this is helpful depends on your domain architecture. In my own workplace, querying remote domain controllers is very expensive. Our site domain controller is a global catalog, though, so searching it for forest information is very fast.
I think that you can simply drop the -Server from Get-ADUser. Since Get-ADGroupMember returns a ADPrincipal[] type, every user contains a fully qualified DistinguishedName, which implies the domain ("server") that the results come from.
Yes, you are right in thinking that essentially (pesudocode):
"contoso.com\user" | Get-ADUser -Server "DC01.theOtherContoso.com"
Will not work. And when piping from Get-ADGroupMember, you get the error:
Get-ADUser : A referral was returned from the server
If you run the same query, but omitting the -Server portion from the Get-ADUser portion, it will use the distinguished name to figure out where to pull the information:
$GM = Get-ADGroupMember -Server $dom -Identity $G.name -Recursive | Get-ADUser -Properties *
It should return you the user objects that you need.

Powershell using Add-ADGroupMember throwing error

I'm using the following code to try to remove & add users to ActiveDirectory groups:
import-module ActiveDirectory
$logs = "D:\logs"
$user = "TempValue"
$group = Get-ADGroup "SomeValue"
$date = (Get-Date).ToString('yyyyMMdd')
$userPrincipal = (get-aduser "$user" -server 123 -properties *).userPrincipalName
$newUser = (get-aduser -filter "userPrincipalName -like '$userPrincipal'" -server 456)
$FileSystem = New-Object -com "Scripting.FileSystemObject"
$stream = $FileSystem.CreateTextFile("$logs\changedgroups-$date.txt", $True, $True)
Remove-ADGroupMember -Identity "$group" -Member "$user" -Confirm:$false
$stream.WriteLine("Removed $user from $group")
Add-ADGroupMember -Identity $group -server 123 -Member $newUser
$stream.WriteLine("Added $newUser to $group")
Scenario: Both domains are in the same forest Domains are in separate forests. I'm on domain "123" trying to remove a user from a group in domain 123 and add a user to that same group from domain 456.
Problem: It adds the user from domain 456, but it shows the user as a Foreign Security policy and gives the message "Note that this object is just a placeholder for a user or group from a trusted external domain." Any idea why?
I've run into this limitation of add-adgroupmember as well. To get around it switch to Set-ADGroup a few examples are provided below. You can specify the DN,SID or samaccountname withing the add or remove
Set-ADGroup -Add:#{'Member'="CN=Group3,CN=Users,DC=GLOBOMANTICS,DC=COM"} -Identity:"CN=Group1,CN=Users,DC=GLOBOMANTICS,DC=COM" -Server:"DC.GLOBOMANTICS.COM"
Set-ADGroup -Identity:"CN=Group1,CN=Users,DC=GLOBOMANTICS,DC=COM" -Remove:#{'Member'="CN=Group3,CN=Users,DC=GLOBOMANTICS,DC=COM"} -Server:"DC.GLOBOMANTICS.COM"

List AD users who do not belong to one of several groups

First up, I am not a script writer, so I apologise if this sounds like a real newbie question.
I am trying to write a Powershell query to list all user accounts within a certain OU sub-tree who do not belong to at least one of 4 groups.
As far as I can tell you cannot query this directly on the AD User object, so you need to iterate through the groups to get the membership, but I'm not clear on how to go about this across multiple groups.
I have put together a script that can find all users, add them to a temporary group and then remove them if they belong to one of the four other groups, but this looks like a horrible way to approach it, so I am hoping someone has a better solution.
Here's what I currently have (don't laugh) :-(
Import-Module ActiveDirectory
$groupname = "TempGroup"
$excludegroup1 = "Group1"
$excludegroup2 = "Group2"
$excludegroup2 = "Group4"
$excludegroup2 = "Group4"
$users = Get-ADUser -Filter * -SearchBase "ou=xxx,dc=xxx,dc=xxx" -SearchScope Subtree
foreach($user in $users)
{
Add-ADGroupMember -Identity $groupname -Member $user.samaccountname -ErrorAction SilentlyContinue
}
$members = Get-ADGroupMember -Identity $groupname
$excludemembers = Get-ADGroupMember -Identity $excludegroup1
foreach($member in $excludemembers)
{
Remove-ADGroupMember -Identity $groupname -Member $member.samaccountname
}
$members = Get-ADGroupMember -Identity $groupname
$excludemembers = Get-ADGroupMember -Identity $excludegroup2
foreach($member in $excludemembers)
{
Remove-ADGroupMember -Identity $groupname -Member $member.samaccountname
}
$members = Get-ADGroupMember -Identity $groupname
$excludemembers = Get-ADGroupMember -Identity $excludegroup3
foreach($member in $excludemembers)
{
Remove-ADGroupMember -Identity $groupname -Member $member.samaccountname
}
$members = Get-ADGroupMember -Identity $groupname
$excludemembers = Get-ADGroupMember -Identity $excludegroup4
foreach($member in $excludemembers)
{
Remove-ADGroupMember -Identity $groupname -Member $member.samaccountname
}
All help gratefully accepted.
All users, computers, groups and contacts (and possibly other objects) in Active Directory have a property called memberof. This property contains the distinguished names of all groups from the whole forest that this entity is a member of, as the attribute's name implies.
Given this information, you can now construct an ldap search query to find all entities that are not members of at least one of those groups:
(!(|(memberof=CN=Group1,dc=domain,dc=com)(memberof=CN=Group3,dc=domain,dc=com)(memberof=CN=Group3,dc=domain,dc=com)))
Other conditions may be included as necessary.
If you need to obtain the distinguished names of those groups first, you can either hard-code them in your filter or do a normal Powershell search for the groups and then read their distinguished names.
You can use the ldap query via the command's -LDAPFilter parameter.
In case anyone is interested, this is the code I have now. It uses a group, which it flushes each run, because then I can simply double-click a user to get into their object and add them to the group they're missing from.
Import-Module ActiveDirectory
$groupname = "NotInGroups"
$members = Get-ADGroupMember -Identity $groupname
foreach($member in $members)
{
Remove-ADGroupMember -Identity $groupname -Member $member.samaccountname
}
$users = Get-ADUser -Filter {((memberof -notlike "CN=Group1,DC=domain,DC=local") -AND (memberof -notlike "CN=Group2,DC=domain,DC=local") -AND (memberof -notlike "CN=Group3,DC=domain,DC=local") -AND (memberof -notlike "CN=Group4,DC=domain,DC=local"))} -SearchBase "ou=users,dc=domin,dc=local" -SearchScope Subtree
foreach($user in $users)
{
Add-ADGroupMember -Identity $groupname -Member $user.samaccountname -ErrorAction SilentlyContinue
}