Adding Users to Groups from another Domain with Powershell - powershell

I have been tasked with creating a PowerShell script that copies Active Directory Group Memberships from a specified Source User (as a template) to a specified Target User. These users can be in one of two domains: Domain_A and Domain_B. The groups are all located in Domain_B.
The issue that I'm running into is that when I specify that both of the users are in Domain_A, it attempts to look for the groups in Domain_A, when in reality the groups are all in Domain_B (this throws an error saying that it can't find the groups). There is a 2 way trust between the domains as they are all located in the same forest.
How can I make it so that it will still specify the domains that the users are located in, but it will also specify the domain that the groups are located in? Here is a copy of my source code for reference (edited to remove the server names):
$Source_Server = Read-Host "Please enter the Source Server: "
$Source_UPN = Read-Host "Please enter the Source UPN: "
$Target_Server = Read-Host "Please enter the Target Server: "
$Target_UPN = Read-Host "Please enter the Target UPN: "
Try {
Get-ADUser -Identity $Source_UPN -Properties memberof -Server$Source_Server |
Select-Object -ExpandProperty memberof |
# Find Properties of the memberships of the Source User
Add-ADGroupMember -Members $Target_UPN -Server $Target_Server |
Select-Object -ExpandProperty SamAccountName
# Copy the group memberships of the Source User to the Target User.
}
Catch {
$Error_Message = $_.Exception.Message
Write-Host $Error_Message
Write-Host -NoNewLine "Press any key to exit..."
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
# Exits the program
}
If (!$Error) {
"Group Copy Successful."
$Error_Message = "No errors occured."
# Shows that it ran error-free
Write-Host -NoNewLine "Press any key to exit..."
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
# Exits the program
}

If you're trying to add the user in Domain B to the group in Domain A, you need to fix the Server parameter here to go to the Source Server:
Add-ADGroupMember -Members $Target_UPN -Server $Target_Server

Related

Moving user in Active Directory using PowerShell won't work

I am trying to make a script that allows new users on the domain to be put into certain groups based on their tag e.g [DALT]. When I run the script it should work properly as it uses the correct OUs and target path but it seems to not work the way I expect it to. I use a credential saved on my D drive as the cred to have admin rights.
$deviceName = Hostname
$deviceName = $deviceName -replace '[^a-zA-Z]', ''
$defaultName = Hostname
# Import Cred for access to change Dir
$credential = Import-Clixml -Path 'D:\backgroundProcess\cred.xml'
$credential
# Directing users to different part of AD depending on deviceName
# Action House (Branch of Company)
if ($deviceName -eq 'DALT') {
Move-ADObject -Identity "CN=$defaultName,CN=Computers,DC=internal,DC=ttlhidden,DC=co,DC=uk" -TargetPath "OU=Windows,OU=Laptop,OU=Computers,OU=DEKRA,DC=internal,DC=ttlhidden,DC=co,DC=uk"
Write-Host "$defaultName added to Hidden group."
gpupdate /force
}
else {
Write-Host "Sorry, $deviceName is not a verified name, please contact Max for more information."
}
Remove-Item -Path 'cred.xml'
It always seems to render the else option even if my computer has DALT at the start.

Powershell Get Distinguished Name of Exchange Server

I'm searching to gather the Distinguished name of an exchange server to show it's version.
Here's the code I already have, in which is missing the automated function allowing to gather the DN, also, I'm loading the script from my active directory:
$Dinstinguishedname = Read-Host -Prompt 'Input Distinguished Name of your exchange server (e.g. :CN=Servers,CN=Exchange Administrative Group (FYDIBOHF23SPDLT),CN=Administrative Groups,CN=Exchange-Domain-Enzo,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=domain,DC=eu)'
$conteneur=get-adobject "$Dinstinguishedname"
cd AD:\$conteneur
$a=get-childitem
foreach ($i in $a){ get-adobject $i -Properties serialnumber}
Remove-Variable -Name conteneur,a,i
cd C:
Write-Host "variable cache cleared :p" -fore Red
#CN=Servers,CN=Exchange Administrative Group (FYDIBOHF23SPDLT),CN=Administrative Groups,CN=Exchange-Domain-Enzo,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=domain,DC=eu

Powershell Get AD user group query

I am trying to create a script that will allow me to enter a user name and will then present me with all the groups that the user is a member of in AD. I have the following code which works when i run it in Powershell ISE but when i just run the script in Powershell it allows me to enter the username but closes as it has queried AD. It does not print the results out on the screen.
$username = Read-Host 'Please enter Username!'
get-aduser $username -Properties memberof | select -expand memberof
If you are pasting the code into an already open PowerShell terminal then yes, that is definitely weird.
If you are right clicking and "Running with PowerShell" then this is the expected behaviour because the script has finished. You'll need to tell the script to stay open after it has retrieved the information. The easiest way to do this is by telling the script to wait for your input using Read-Host
$username = Read-Host 'Please enter Username!'
get-aduser $username -Properties memberof | select -expand memberof
Read-Host 'Done!'
UPDATE
Using an if statement wouldn't be feasible since it only catches terminating errors and Get-ADUser doesn't return terminating errors you would need to use a try/catch block. I over engineered this solution use to show you how it could be done using different PowerShell features :)
#Function to search for the user
function searchUser{
Param([string]$userName)
try{
Get-ADUser -Identity $userName -Properties MemberOf | Select-Object -ExpandProperty MemberOf
}catch{
return $false
}
}
#Ask the user for input until a valid username is entered
do {
$userInput = Read-Host "Enter a username: "
}until ($Output = searchUser -userName $userInput)
#Output the value from the searchUser function
Write-Host $Output

Powershell command execution order problem

I'm new in learning Powershell and I ran into a problem that makes me go insane. I want to write a simple Powershell script, that can be used to get both the group memberships of certain ActiveDirectory users, and the users of certain ActiveDirectory groups, and in the end gives the option to write the result on the console, or save it as csv.
Everything works perfectly fine, except no matter what I do, I can't stop the window from closing right after it writes the results on the console. I know that I can run a PS1 from command line in a way that doesn't allow the window to close, but I'd like Powershell do it by itself.
I tried to use both "pause" and Read-Host after the query script, but the stop event always happens BEFORE the result gets out on the console, no matter what's the order between the two of them. I simply cannot understand why the order of the execution of the two commands is backwards. Could you give me some insight why Powershell does it?
$nameofgroup = Read-Host -Prompt "`nPlease enter the name of the group!`n"
Get-ADGroupMember -identity $nameofgroup | Get-ADObject -Properties description, samAccountName | select #{n='Name'; e='name'}, #{n='Description'; e='description'}, #{n='Username'; e='samAccountName'}
$temp = Read-Host "Press Enter to continue..."
So you need to explicitly tell powershell to output the string. I also added in some error handling for you, so you don't have to run the script every time. Like if the group was typed wrong or doesn't exist.
Do
{
$nameofgroup = Read-Host -Prompt "`nPlease enter the name of the group!`n"
try
{
Get-ADGroupMember -identity $nameofgroup | Get-ADObject -Properties description, samAccountName | select #{n='Name'; e='name'}, #{n='Description'; e='description'}, #{n='Username'; e='samAccountName'} | Out-String
$errorMessage = 'False'
Read-Host -Prompt 'Press Enter key to exit'
}
catch
{
Write-Host "Could not find group please try again"
$errorMessage = 'True'
}
}
while($errorMessage -eq 'True')

Disabling ESET Secure Authentication for AD User accounts

Would anybody have an insight on how to disable a user's ESET Secure Authentication setting with a Powershell script?
I have a script that disables a users Active Directory account, resets the password, and moves it to a new OU but now I'm stumped on how to disable the properties related to their ESET information. From the ADUC GUI you can uncheck the box for their hardware token and REVOKE the key, so I would imagine there's a way to do it with a script that I can include in my current script.
# Imports module for running commandlets against Active Directory, and inputs user name
# into variable.
# Enter-PSSession DomainController // Need to run this commandlet from your local
# machine first.
Echo "You are about to disable a user account. Verify your information!"
Read-Host "Press ENTER to continue."
Import-module ActiveDirectory
$User1 = Read-Host -Prompt 'Enter the username of the employee you wish to change'
# Disables named users ActiveDirectory Account.
# "Locked Account" does not show but need to right click to enable
Disable-ADAccount -Identity $User1
# Adds AD group "Disabled Users" to named user group membership
Add-ADGroupMember -Identity 'Disabled Users' -Member $User1
# Set named users primary group to "Disabled Users"
Set-ADUser -Identity $User1 -Replace #{PrimaryGroupID="0000"}
# Removes groups assigned to named users membership
Get-ADUser -Identity $User1 -Properties MemberOf | ForEach-Object {
$_.MemberOf | Remove-ADGroupMember -Members $_.DistinguishedName -Confirm:$false
}
# Changes named users password based on Administrators input
$newpwd = Read-Host "Enter the new password" -AsSecureString -WhatIf
Set-ADAccountPassword $User1 -NewPassword $newpwd –Reset -WhatIf
# Moves named user from current OU to "Employee DISABLED\DISABLED" container
get-aduser $User1 | move-adobject -targetpath
"ou=DISABLED,ou=Employee DISABLED,dc=DOMAINNAME,dc=com"
# Much respect due to the onesixooh!
Read-Host "Press ENTER to finish"
Write-Host " **********************************************************
>>> Get the money. Dolla dolla bill y'all. <<<
**********************************************************"
Any advice is greatly appreciated.
Try using the Windows Server ADAC (AD Admin Center) to write this code for you, to see if that gets you closer to your end goal.
Open ADAC
Use the GUI to do the steps you need
Open the PowerShell History Viewer
Copy and paste into your favorite PoSH Editor (ISE, VSCode, etc...) and tweak
as needed.