2. Active Directory Tasks - Powershell
2.99 Moving Users and Computers to a New Organizational Unit
Move a User or Computer to a New OU
the Move-ADObject
cmdlet is used to move users and computers to a new OU, to know the syntax of it:
Get-Command Move-ADObject -Syntax
the -Identity
parameter is used to specify the object to move, and the -TargetPath
parameter is used to specify the new OU to move the object to.
Note: you need the enter the full LDAP path or SID of the object, you can’t use the SamAccountName.
Here is how to move the user “Ammar Saber” (who is in IT OU) to the “HR” OU:
Move-ADObject -Identity "CN=Ammar Saber,OU=IT,DC=tinker,DC=lab" -TargetPath "OU=HR,DC=tinker,DC=lab"
the same syntax applies to computers:
Move-ADObject -Identity "CN=WS-IT-01,OU=IT-Workstations,DC=tinker,DC=lab" -TargetPath "OU=HR-Workstations,DC=tinker,DC=lab"
Move Multiple Users or Computers to a New OU
if you have a Text file with the users or computers you want to move, like this:
Ammar Saber
Khaled Ahmed
you can use the following script to move them to a new OU (for example “HR” OU):
# Import the list of usernames from the text file
$Users = Get-Content -Path "C:\Users\domain-admin\Desktop\users.txt"
# Define the target OU (Distinguished Name)
$TargetOU = "OU=HR,DC=tinker,DC=lab"
# Loop through each user and move them to the new OU
foreach ($User in $Users) {
# Find the user in AD
$UserObject = Get-ADUser -Filter "Name -eq '$User'" -Properties DistinguishedName
if ($UserObject) {
# Move the user to the new OU
Move-ADObject -Identity $UserObject.DistinguishedName -TargetPath $TargetOU
Write-Host "Moved user $User to $TargetOU"
} else {
Write-Host "User $User not found in Active Directory"
}
}
for computers, you can use the following script:
# Import the list of computer names from the text file
$Computers = Get-Content -Path "C:\Users\domain-admin\Desktop\computers.txt"
# Define the target OU (Distinguished Name)
$TargetOU = "OU=HR,DC=tinker,DC=lab"
# Loop through each computer and move it to the new OU
foreach ($Computer in $Computers) {
# Find the computer in AD
$ComputerObject = Get-ADComputer -Filter "Name -eq '$Computer'" -Properties DistinguishedName
if ($ComputerObject) {
# Move the computer to the new OU
Move-ADObject -Identity $ComputerObject.DistinguishedName -TargetPath $TargetOU
Write-Host "Moved computer $Computer to $TargetOU"
} else {
Write-Host "Computer $Computer not found in Active Directory"
}
}
Explanation:
- The script reads a list of computer names from computers.txt.
- It defines the target Organizational Unit (HR in this case).
- It loops through each computer name, finds the corresponding Active Directory object, and moves it to the new OU.
- If the computer is not found, it prints a message indicating that.