I was working on automating few Active directory groups using powershell, I encountered a issue where my scripting solution was running in one domain
but the group resides in another domain. Below powershell command was resulting in error as by default AD module searches on the domain from which it is running.
- First step is to get the user object using AD module get-aduser command and direct it to the domain where the it exists.
$getmemberobject = get-aduser -Filter “UserPrincipalName -eq ‘$upn'” -server $domainwhereexists
- Second step is to get the group object in the same way using get-adgroup direct it to the domain using the server parameter.
$getgroupobject = get-adgroup -identity $groupinparticulardoamin -server $domainwhereexists
- Ones above two steps are done, you can use your ADD-ADGroupmember cmdlet like below with distinguished name properties and directing it to the domain where this operation should happen.
Add-ADGroupMember -identity $getgroupobject.DistinguishedName -members $getmemberobject.DistinguishedName -server $domainwhereexists
Update: 9/29/202 as tested by Aston, use object instead of property (as many have encountered errors using the property)
Add-ADGroupMember -identity $getgroupobject -members $getmemberobject -server $domainwhereexists