Powershell using Add-ADGroupMember throwing error - powershell

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"

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.

Powershell Script to get all groups containing specific name

Okay, so I am a little new to powershell and I am trying the best I can but cannot seem to get this.
The way my directory is setup is that each organization has their own "Password Reset Group" I will have a scheduled task setup that runs based on the event log entry "Directory Service Change". The script's job is to find members in the groups and reset their password back to their employeeNumber, make the user change the password at next logon and then remove the user from the group. I seem to be having issues getting the syntax correct.
Try {
$GroupDN = (Get-ADGroup -Filter {Name -like '*Password Reset Group*'}).DistinguishedName
}
Catch {
Write-Host "Unable to locate group: $Group because ""$($Error[0])""" -ForegroundColor Red
Exit
}
ForEach ($User in (Get-ADUser -Filter * -Properties MemberOf,employeeNumber))
{ If ($User.MemberOf -contains $GroupDN)
{ $password = "$($_.employeeNumber)new!" | ConvertTo-SecureString -AsPlainText -Force
Set-ADAccountPassword -Identity $User -NewPassword $password -Reset
Remove-ADGroupMember -Identity "$GroupDN" -Members $User
}
}
Good to see you came up with your own answer, but you can simplify this by just using ...
Get-ADPrincipalGroupMembership
# get function / cmdlet details
(Get-Command -Name Get-ADPrincipalGroupMembership ).Parameters
Get-help -Name Get-ADPrincipalGroupMembership -Full
Get-help -Name Get-ADPrincipalGroupMembership -Online
Get-help -Name Get-ADPrincipalGroupMembership -Examples
# Example 2: Get group memberships for the Administrator
Get-ADPrincipalGroupMembership -Identity Administrator
... which lists all the groups a user belongs to.
So, your adjustment could be just this...
Get-ADUser -Filter * |
ForEach{
# "`n--- Processing user $($PSItem.SamAccountName) ---`n"
If ($TargetGroup = (Get-ADPrincipalGroupMembership -Identity $PSItem.SamAccountName) -match 'Password Reset Group')
{
$password = "$($PSItem.employeeNumber)new!" |
ConvertTo-SecureString -AsPlainText -Force
Set-ADAccountPassword -Identity $PSItem.SamAccountName -NewPassword $password -Reset
Remove-ADGroupMember -Identity $TargetGroup.SamAccountName -Members $PSItem.SameAccountName
}
}
As for …
Okay, so I am a little new to powershell
… that is all well a good, but it is prudent for you to spend the time getting ramped up on PowerShell to limit / avoid guessing, misconception, frustration, bad habits, errors, etc., that you are going to continue to encounter (even the most experienced of us do and learn from it and each other). There are tons of no cost / free resources all over the we for you to leverage.
Live on YouTube, MVA, MSDN Channel9 for all the video training.
Use tools that will write the code for you, that you can save and tweak as needed later. Especially when it comes to ADDS.
Active Directory Administrative Center: Getting Started
Active Directory Administrative Center
Step-By-Step: Utilizing PowerShell History Viewer in Windows Server 2012 R2
Free Books and references
Using the information given to me by #AdminOfThings. I was able to write the code I wanted. It took a lot of playing around but here it is:
ForEach ($GroupDN in (Get-ADGroup -Filter {Name -like '*Password Reset Group*'}).DistinguishedName)
{ ForEach ($User in (Get-ADUser -Filter * -Properties MemberOf,employeeNumber))
{ If ($User.MemberOf -contains $GroupDN)
{ $password = $User.employeeNumber | ConvertTo-SecureString -AsPlainText -Force
Set-ADAccountPassword -Identity $User -NewPassword $password -Reset
Set-ADUser -Identity $User -ChangePasswordAtLogon $true -PasswordNeverExpires $false
Remove-ADGroupMember -Identity "$GroupDN" -Members $User -Confirm:$false
}
}
}

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.

PowerShell script runs with error first time, but correctly second or third time

I have a script to disable users in AD with the following steps:
asks for username
set "domain users" group as primary group
disable users in AD
move to disabled OU
clear Manager from AD
remove all groups except 'domain users'
Add disabled_mailboxes to the user
Hide account from exchande list
Now, when i try the first time it does not work. i have to run it several times like 2 3 and 4 times to work.
When i run it step by step, it work fine also from the first time
and here is the script:
$username = Read-Host -Prompt 'Enter Username'
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
Import-Module ActiveDirectory
$user = Get-ADUser -Filter {(SamAccountName -eq $username)} -Properties MemberOf
#set "domain users" group as primary group
$group = get-adgroup "Domain Users" -properties #("primaryGroupToken")
get-aduser $username | set-aduser -replace #{primaryGroupID=$group.primaryGroupToken}
#disable users in AD
Get-ADUser -Filter {(SamAccountName -eq $username)} | Disable-ADAccount -ErrorAction SilentlyContinue
#move to disabled OU
Get-ADUser -Filter {(SamAccountName -eq $username)} | Move-ADObject –TargetPath “OU=Users,OU=Disabled Objects,DC=xxxxxxx,DC=xxx,DC=XXX”
#clear Manager from AD
Get-ADUser -Filter {(SamAccountName -eq $username)} | Set-ADUser -Clear manager
#-------------------------
#remove all groups except 'domain users'
Get-ADPrincipalGroupMembership -Identity $username | % {Remove-ADPrincipalGroupMembership -Identity $username -MemberOf $_ -Confirm:$false -ErrorAction SilentlyContinue}
#code can be removed.
#$group = $user | Select-Object -ExpandProperty MemberOf
#Remove-ADGroupMember -Identity $group -Members $user.SamAccountName -Confirm:$false -ErrorAction SilentlyContinue
#-------------------------
#Add disabled_mailboxes to the user
Add-ADGroupMember -Identity 'disabled_mailboxes' -Member $User.SamAccountName -ErrorAction SilentlyContinue
#-------------------------
#Hide account from exchande list
Set-Mailbox -identity $user.SamAccountName -HiddenFromAddressListsEnabled $true -ErrorAction SilentlyContinue
Windows 2012R2, Exchange 2010
Can anyone help with that???
Thanks
Mina
Do not use Get-ADUser repeatedly in the sequential lines. Just use the existing $user variable that you've just populated with values. Most likely you are hitting an issue that Get-ADUser returns old cached value for DN right after you run Move-ADObject (this changes the DN of the user), and since all queries use DN to locate the user, you get the error. The second run has the target user already in the destination OU, so no errors arise.

Add users from another domain to AD group

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
}