PowerShell script to add user to different domain in Active Directory - powershell

I'm trying to add users from a csv file who are from domain1 to a security group in domain2 using the following script.
Import-Csv -Path "C:\Temp\test.csv" | ForEach-Object {Add-ADGroupMember -Server domain1.company.com -Identity "testSecurityGroup" -Members $_.'userName'}
But because the users are on a different domain than the security group, I'm getting this error message below. It cannot find the security group I want under the domain1.company.com domain that I wrote in my script.
Here's the error message:
Add-ADGroupMember : Cannot find an object with identity: 'testSecurityGroup' under: 'DC=domain1,DC=company,DC=com'.

You are trying to add the users from Domain1 to a security group in Domain2, but the below script tries to add the users to a security group in Domain1 which does not exist.
Import-Csv -Path "C:\Temp\test.csv" | ForEach-Object {Add-ADGroupMember -Server domain1.company.com -Identity "testSecurityGroup" -Members $_.'userName'}
So, you get the below error :
Add-ADGroupMember : Cannot find an object with identity: 'testSecurityGroup' under: 'DC=domain1,DC=company,DC=com'.
Instead, you can use the below command to add the users in Domain 1 to a security group in Domain2
Import-Csv -Path "C:\Temp\test.csv" | ForEach-Object {Add-ADGroupMember -Server domain2.company.com -Identity "testSecurityGroup" -Members $_.'userName'}

Related

Powershell: Export group members from external domain

I want to export users of some large groups.
The groups are filled with other groups and the members of those groups are users from a trusted external domain.
When I run this script if gives an error:
$Users = Get-ADGroupMember -Identity 'Group' -recursive |
Where {$_.ObjectClass -eq 'User'} |
Get-ADUser -Properties SamAccountName |
Select-Object SamAccountName
Error: The operation being requested was not performed because the user has not been authenticated.
And that's the other domain that requests authentication.
How can I achieve this in the script?
Thanks
Whenever you run an AD group cmdlet, it uses your logged-in credentials to query Active Directory. This says you need to be on a domain joined computer logged in as an AD user that has permission to query.
You are on a workgroup computer or need to authenticate to AD as a different user. Then you need to provide credentials. Like other ps cmdlets, Get-ADGroupMember has a -Ceedential parameter and This parameter allows you to specify a username and password to use for the authentication.
This will show a dialog to prompt you for your credentials:
$Users = Get-ADGroupMember -Identity 'Group' -recursive -Credential (Get-Credential) | Where {$_.ObjectClass -eq 'User'} | Get-ADUser -Properties SamAccountName | Select-Object SamAccountName
Or you can specify credentials:
$cred = New-object System.Management.Automation.Pscredential User, Password
AND -Credential $cred

How to run this script against another domain

I have the script below to give me the distinguished name for groups in a spreadsheet I have. The issue is, the groups are located in another domain. How do I point my script to that domain? Issue is I know I have to be logged in to that domain to run it but I cant.
$Groups = Get-Content -Path C:\Scripts\DistinguishedName.csv
ForEach ($Group in $Groups) {
Get-ADGroup -Identity $Group | Select-Object distinguishedName
}
The cmdlets in the Active Directory module support passing in the value of the domain controller you are wanting to query. By default when you call Get-ADGroup (or any of the other) it will validate what domain it should query by checking the domain of your current machine.
The other option is to provide the -Server (doc) with the value of the Active Directory Domain Services you want to execute your query against.
You can also provide the -Credential parameter with a PSCredential object that contains your login for that other domain. This is required if the current login of your PowerShell session is not authorized to authenticate against that other domain.
So your example script would look something like this:
$AdDomain = "whatever.company.local"
$adCred = Get-Credential
$Groups = Get-Content -Path C:\Scripts\DistinguishedName.csv
ForEach ($Group in $Groups) {
Get-ADGroup -Identity $Group -Server $AdDomain -Credential $adCred | Select-Object distinguishedName
}

Get-ADUser using old pre-Windows 2000 Logon name instead of CN

I'm trying to use Add-ADGroupMember cmdlet in PowerShell, but I've realized PS doesn't recognize the object if I use the CN, and it only seems to recognize the pre-Windows 2000 logon name.
That attribute had a character limitation of 20 characters, so some of our accounts have different CNs and Pre-Windows 2000 logon names.
My whole process is:
Step 1: Get a list of my users (this gives me the legacy pre-Windows 2000 logon names):
Get-ADUser -Filter {department –notlike “Field”} –SearchBase “OU=Accounts,OU=HQ,OU=Production,DC=MYDC,DC=MYDC1,DC=MYDC2” -Properties department | select name | Out-file C:\Users\Public\Users.txt
Step 2: Add those users to my security group:
$UserList = Get-Content "C:\Users\Public\Users.txt"
$GroupName = "MY-SEC-Group"
$Members = Get-ADGroupMember -Identity $GroupName -Recursive | Select -ExpandProperty SAMAccountName
ForEach ($user in $UserList)
{
If ($Members -contains $user)
{
Write-Host "$user is member of $GroupName"
}
Else
{
Write-Host "$user is not a member. Attempting to add now, run script again for verification"
Add-ADGroupMember -Identity $GroupName -Members $User
}
}
For all accounts where the legacy logon name and the CN are the exact same, there are no issues. But in situations where they are different, I get the error "Object not found"
Is there a better/more up-to-date cmdlet to use? Maybe one that relies on the CN instead of the legacy logon name? Or do I need to add in CN to all my scripts now?
Get-ADGroupMember returns objects that point to the concrete user in ActiveDirectory and contain different fields including distinguishedName, SamAccountName , SID, Name and so on. In your code you create a txt file with Names (not SamAccountName) but use SamAccountName in Get-ADGroupMember. So, you just compare names with SamAccountName values (that's incorrect).
Just replace
select name | Out-file C:\Users\Public\Users.txt
with
select SamAccountName | Out-file C:\Users\Public\Users.txt
SamAccountName (just as SID) is the unique attribute in AD -
https://blogs.technet.microsoft.com/389thoughts/2017/02/03/uniqueness-requirements-for-attributes-and-objects-in-active-directory/ so, you should use it in your code.

Remove full access permissions of all disabled users on shared mailboxes with exchange management shell

I’m looking for a powershell exchange script to remove Full access permissions of all disabled users on all shared mailboxes in a specific OU.
This is what I got so far
Remove-MailboxPermission -Identity Sharedmailbox -AccessRights Fullaccess -InheritanceType all -user DisabledUser -Confirm:$false | where {$_.UseraccountControl -like "*accountdisabled*"}
Its seems to work but I’m not sure about the last piece of het script if it will check for “accountdisabled”
Then I created a variable so it will check only one specific OU
$ou = Get-ADUser -SearchBase "OU=Functional Mailboxes,OU=Generalaccounts,DC=DOMAIN,DC=COM" -Filter * foreach ($user in $ou)
Remove-MailboxPermission -Identity "$ou" -AccessRights Fullaccess -InheritanceType all -Confirm:$false | where {$_.UseraccountControl -like "*accountdisabled*"}
The script is checking the right OU but I'm still looking for the last part where it will automatically remove full access permissions of the disabled users ONLY.
Can someone show me the way?
Instead of trying to screen for disabled users after removing the mailbox permissions (which is what your Remove-MailboxPermission ... | Where-Object ... appears to be intended to do - except that the way you wrote it, it's only checking for disabled state after removing the permissions), try selecting for the disabled accounts first, then passing only the disabled accounts to Remove-MailboxPermission:
Get-ADUser -SearchBase ... -filter {Enabled -eq $false} | Remove-Mailbox ...
(replacing ... with the appropriate SearchBase or parameters for Remove-Mailbox, using $_ for the identity of the ADUser whose mailbox permissions you're removing.)

Error handling per user

I am trying to list the membership list for each user in the Active Directory Domain. I created the following line:
foreach($_ in $(Get-ADUser -Filter *).Name){
Get-ADPrincipalGroupMembership -Identity $_ | select Name,Groupscope,Groupcategory| sort Name
}
The problem is that running this line of code causes the following error to come up when a user doesn't have any groupmembership.
Get-ADPrincipalGroupMembership : Cannot find an object with identity: 'TEST USER'
under: 'DC=contoso,DC=com'.
Adding -Erroraction Silentlycontinue behind Get-ADPrinicpalGroupMembership does not mitigate the problem. I'd rather not mess around with $ErrorAction. However, changing $ErrorAction to "silentlycontinue" and changing it back after the line completes does work. Not a pretty solution though. Is there any way to prevent the error showing otherwise?
Output for noam's solution: (Only shows a full list of groups available, not the memberships of the users)
name groupScope groupCategory
---- ---------- -------------
Administrators DomainLocal Security
Distributed COM Users DomainLocal Security
Domain Admins Global Security
Domain Users Global Security
Enterprise Admins Universal Security
Group Policy Creator Ow... Global Security
HelpLibraryUpdaters DomainLocal Security
Schema Admins Universal Security
TESTGROUP1 Global Security
Domain Guests Global Security
Guests DomainLocal Security
Denied RODC Password Re... DomainLocal Security
Domain Users Global Security
You could retrieve the MemberOf property and only run Get-ADPrincipalGroupMembership when that property is not null.
$all = Get-ADUser -filter * -property memberOf
foreach ($usr in $all) {
if ($usr.MemberOf) {
$groups = $usr | Get-ADPrincipalGroupMembership | select name, groupScope, groupCategory
$usr.name + " belongs to the following groups:`n"
$groups | sort name | ft -auto
} else {$usr.name + " does not belong to any groups.`n"}
} #close foreach
Custom objects can also be useful for this kind of reporting.
Get-Member is useful for exploring object properties.
Get-ADUser joeUser -Property * | gm | where {$_.memberType -eq "Property"}
I am not sure of the behavior of these cmdlets, but the error you are seeing may be caused by using only the Name property value to identify the object and not it's DN or other unique identifier (Get-ADPrincipalGroupMembership Documentation. Try piping the output of Get-ADUser to Get-ADPrincipalGroupMembership to see if the issue still occurs (see example below). Also, you may want to pipe the contents of Get-ADUser to the next cmdlet so you don't have to store the information returned by Get-ADUser in memory before processing.
Get-ADUser -Filter * | Get-ADPrincipalGroupMembership
If the issue still exists:
You could use a try/catch block:
Get-ADUser -Filter * | %{ `
try
{
Get-ADPrincipalGroupMembership $_
}
catch [Microsoft.ActiveDirectory.Management.ADIdentityResolutionException]
{
#Log
Write-Host "not found"
}
}