How to fix Cannot find an object with Identity in Powershell Script - powershell

I'm trying to get this Powershell script to transfer group membership from one user to another in Active Directory. I am getting the error below stating it can't find the object with identity. This is odd because the user is in AD in the domain that I called upon and the first user that I am transferring the membership from is found without any issues. Any ideas?
Get-ADUser -server "ngcore01.test.hawaii.local" -Identity user11 -Properties memberof |
Select-Object -ExpandProperty memberof
Add-ADGroupMember -Member user22
This is the error:
Add-ADGroupMember : Cannot find an object with identity: 'user22' under: 'DC=test,DC=hawaii,DC=local'.
At line:3 char:1
+ Add-ADGroupMember -Members user22
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (user22:ADGroup) [Add-ADGroupMember], ADIdentityNotFoundException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.
Management.Commands.AddADGroupMember

The error message shows that the Add-ADGroupMember cmdlet has difficulties finding a group with Identity user22 and that is because you do not supply this Identity value. (See: Add-ADGroupMember)
The memberof property returned by Get-ADUser is a collection of DistinguishedNames of the user’s direct group membership and you need to loop over the returned values in this collection to use as -Identity parameter on the call to Add-ADGroupMember
Try
(Get-ADUser -Server "ngcore01.test.hawaii.local" -Identity user11 -Properties memberof).memberof | ForEach-Object {
Add-ADGroupMember -Identity $_ -Members user22
}

Related

"A referral was returned from the server" in powershell when trying to use Remove-ADGroupMember

Intro
I have a script that works without issue for users in the root domain. Basically what it does is it
Imports a csv of users
Grabs their distinguished name
Sees if their distinguished name exists in a list of distinguished names in a group
If their DN is indeed in the group, remove them from the group.
Issue
However, I am running into issues when trying to remove users in a child domain from a group located in the root domain.
The Error
Remove-ADGroupMember : A referral was returned from the server
At U:\powershell\AD\Remove_users_from_group.ps1:16 char:9
+ Remove-ADGroupMember $groupDN -Members $user -Confirm:$false ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ResourceUnavailable: (CN=GroupA C=Domain,DC=com:ADGroup) [Remove-ADGroupMember], ADRe
ferralException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8235,Microsoft.ActiveDirectory.Management.Commands.RemoveADGroupMember
Code
$csv = Import-Csv -Path "users.csv" -Header 'Username'
$group = 'GroupA'
$groupDN = Get-ADgroup 'GroupA'| Select -Property DistinguishedName
$incount = 0
$notcount = 0
$members = Get-ADGroupMember $group -Server "domain.com" | Select -Property DistinguishedName
ForEach ($Username in $csv) {
$user = $Username.Username
$user = Get-ADUser $user -Server "child.domain.com" | Select -Property DistinguishedName
if ($members -like $user){
Remove-ADGroupMember $groupDN -Members $user -Confirm:$false -Server 'domain.com'
#Set-ADObject -Identity $groupDN -Remove #{member=$($user)}
write-host "Removed:" $user
$incount++
} Else {$notcount++}
}
Write-host "Task complete"
Write-host "Users removed from" $group ":" $incount
Write-host "Users that were not in" $group ":" $notcount
$prompt = Read-Host -Prompt "Press enter to close"
A referral is returned when a DC cannot do what you want to do, but it knows who you need to talk to do what you need to do. In this case, that means it isn't connecting to the correct domain, but Remove-ADGroupMember isn't capable of following the referral. Since you are not specifying the -Server parameter for Remove-ADGroupMember, it's likely connecting to whatever domain you're logged into. The solution is just to use the -Server parameter to make it talk to the correct domain, just like you were doing with Get-ADGroupMember.
Remove-ADGroupMember $groupDN -Members $user -Confirm:$false -Server "domain.com"
I see another problem with your code: You are using the -Recursive parameter with Get-ADGroupMember, meaning that it will return users who are members of groups, where that group is a member of $group. But then you are using Remove-ADGroupMember to remove the user from the group as if it was a direct member of that group. Remove-ADGroupMember will fail for users that are not direct members.

Add-ADGroupMember user from other Domain

This is my situation:
There are two domains: Domain A and Domain B.
Domain A does NOT trust Domain B, Domain B trusts Domain A.
Im executing my command on a computer in Domain B.
I try to add (in the beginning) just one user from Domain A to a AD group in Domain B.
PS> Add-ADGroupMember -Identity GroupOnDomainB -Members DomainA\User1 -Credential DomainA\User1
Add-ADGroupMember : Cannot find an object with identity: 'DomainA\User1' under: 'DC=SUB,DC=DomainB,DC=com'.
At line:1 char:1
+ Add-ADGroupMember -Identity GroupOnDomainB -Members DomainA\User1 - ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (DomainA\User1:ADPrincipal) [Add-ADGroupMember], ADIdentityNotFoundException
+ FullyQualifiedErrorId : SetADGroupMember.ValidateMembersParameter,Microsoft.ActiveDirectory.Management.Commands.AddADGroupMember
This is one of many attempts I made. Nothing successful. First I need to solve this, later it will be a script to load users and groups from a local csv file and of course to add the needed credential as well. I have everything in place but this part, just adding one user from Domain A to a Domain B Group is not working.
I would do it like so:
$DomainA = 'DomainA'
$DomainB = 'DomainB'
$UserName = 'User1'
$GroupName = 'Group'
$User = Get-ADUser -Identity $UserName -Server $DomainA
$Group = Get-ADGroup -Identity $GroupName -Server $DomainB
Add-ADGroupMember -Identity $Group -Members $User
Or:
Add-ADPrincipalGroupMembership -Identity $User1 -MemberOf $Group
You may need to add -Server $DomainB to Add-ADGroupMember/Add-ADPrincipalGroupMembership. It's not entirely clear if that's necessary, and I no longer have access to a forest with multiple domains.

Powershell delete all users in OU

I am trying to delete all users within an OU using powershell, I have the below which gets stuck when it comes to the SAMAccount name, I want it to delete all the found users.
What am I doing wrong here please?
$search="OU=Staff,OU=Users,DC=Testing, DC=Local"
$deletes= Get-ADUser -SearchBase $search -filter * -properties SamAccountName | Select-Object SamAccountName
$numusers=($deletes.count)
echo "$numusers Users Found"
foreach ($delete in $deletes)
{
echo "Deleting user account $delete . . . "
remove-aduser -identity $delete -confirm:$false
}
This is the output. Seemingly going wrong here -- Cannot convert the "#{SamAccountName=bbonhomme}"
7 Users Found
Deleting user account #{SamAccountName=bbonhomme} . . .
Remove-ADUser : Cannot bind parameter 'Identity'. Cannot convert value "#{SamAccountName=bbonhomme}" to type
"Microsoft.ActiveDirectory.Management.ADUser". Error: "Cannot convert the "#{SamAccountName=bbonhomme}" value of type
"Selected.Microsoft.ActiveDirectory.Management.ADUser" to type "Microsoft.ActiveDirectory.Management.ADUser"."
At C:\Users\Administrator\Desktop\import\getadusers.ps1:11 char:29
+ remove-aduser -identity #delete -confirm:$false
+ ~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Remove-ADUser], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.ActiveDirectory.Management.Commands.RemoveADUser
Replace the
$deletes= Get-ADUser -SearchBase $search -filter * -properties SamAccountName | Select-Object SamAccountName
by
$deletes= Get-ADUser -SearchBase $search -filter * -properties SamAccountName
Adding Select-Object implies converting ADUser "object" to "Psobject". By consequence subsequent command remove-ADuser does not recognize this type of object.
Replace also :
remove-aduser -identity $deletes -confirm:$false
By
remove-aduser -identity $delete.SamAccountName -confirm:$false
changed $deletes by $delete (you cannot specify a collection in -Identity parameter)

Get-ADGroup with -recursive is not working?

I am using get-adgroupmember command to fetch all the users in an AD group. -recursive is helping me fetch members from child groups if any in the parent group as well.
However, get-adgroupmember has an upper limit of 5000 entries only.
To tackle this if i use:
Get-ADGroup -Identity "DEPT_120_SA" -server "A" -Properties * | select-object -expandproperty members |get-aduser
this doesnt work as my Parent AD has child ADs and -recursive is not accepted by get-adgroup.
Error:
Get-ADGroup : A parameter cannot be found that matches parameter name
'recursive'. At line:2 char:79
+ Get-ADGroup -Identity "DEPT_120_SA" -server "mhf.mhc" -Properties * -recursive <<<< | select-object -expandproperty members
+ CategoryInfo : InvalidArgument: (:) [Get-ADGroup], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.GetADGroup
my aim is to display username and their mail iDS and this works for me:
Get-ADGroupMember -server $domain -identity $s -Recursive -ErrorAction Stop | Get-AdUser -Properties mail -ErrorAction Stop | select sAmAccountName, Mail
Any workaround ? (I am willing to write a recursive function to fetch large groups, but there must be a shorter and direct way)
The 5000 limit applies only to Get-ADGroupMembers not Get-ADUsers, so we can use the LDAP_MATCHING_RULE_IN_CHAIN matching rule (OID 1.2.840.113556.1.4.1941).
For example:
Get-AdUser -LdapFilter "(memberOf:1.2.840.113556.1.4.1941:=cn=group,cn=users,DC=ad,DC=local)"
where cn=group,cn=users,DC=ad,DC=local is the distinguished name of the group you want members for.

PowerShell script to add computers to group that are not part of another group?

I am trying to pull together a PS script to automatically add computers to a security group that are not part of another group.
In this case, add all computers to group_b that are not part of group_a.
This is what I tried..
#get list of computers from group_a
$tpmobjects = Get-ADGroupMember -Identity "group_a" | Select name
#add computers to group_b that are not in group_a
Get-ADComputer -Filter {SamAccountName -notlike $tpmobjects} | Foreach-Object { Add-ADPrincipalGroupMembership -Identity $_.SamAccountName -MemberOf "group_b" }
The error I get is...
Get-ADComputer : Type: 'System.Object[]' is not supported for extended attribute 'SamAccountName'.
At line:2 char:1
+ Get-ADComputer -Filter {SamAccountName -notlike $tpmobjects}...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-ADComputer], ArgumentException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Commands.GetADComputer
Anyone have a way to do this?
Thanks.
What happens is that Get-ADGroupMember returns multiple objects and the -Filter parameter doesn't support matching against multiple objects.
There are multiple ways around this, but the easiest is to simply filter the output from Get-ADGroupMember with Where-Object:
$Computers = Get-ADGroupMember group_a |Where-Object {$_.objectClass -eq 'computer'}
You also don't need to wrap Add-ADPrincipalGroupMembership in ForEach-Object, it accepts pipeline input, and an ADComputer object can be bound to the -Identity parameter directly without problems:
$Computers |Add-ADPrincipalGroupMembership -MemberOf group_a