Hi there!
I have a fresh installation of Server 2019 with a fresh installation of AD domain service.
I’ve created 2 users:
gilshw & testerb.
the user gilshw is under the ‘Testing’ OU.
the user testerb is under the ‘Users’ OU.
i’m trying to write a powershell script that moves the testerb user to the OU that holds the gilshw user:
function Move-UserToOU {
param (
[string]$exampleUser,
[string]$UserName
)
try {
# Get the DistinguishedName of the exampleUser
$exampleDistinguishedName = (Get-ADUser -Filter {SamAccountName -eq $exampleUser}).DistinguishedName
Write-Host "Target OU DistinguishedName: $exampleDistinguishedName"
# Get the DistinguishedName of the user to be moved
$adUser = Get-ADUser -Filter {SamAccountName -eq $UserName}
if ($adUser) {
Write-Host "User DistinguishedName: $($adUser.DistinguishedName)"
# Move the user to the same OU as exampleUser
Move-ADObject -Identity $adUser.DistinguishedName -TargetPath $exampleDistinguishedName
Write-Host "Moved user '$UserName' to the same OU as '$exampleUser'."
} else {
Write-Host "User '$UserName' not found."
}
} catch {
Write-Host "An error occurred: $_"
}
}
$exampleUser = "gilshw"
$UserName = "testerb"
Move-UserToOU -exampleUser $exampleUser -UserName $UserName
This is the output:
Target OU DistinguishedName: CN=Gil Shwartz,OU=Testing,DC=home,DC=lab
User DistinguishedName: CN=Tester Booga,CN=Users,DC=home,DC=lab
An error occurred: The object cannot be added because the parent is not on the list of possible superiors
What am I doing wrong?
Thanks!