So I've been trying to bulk add users into an OU, and currently I'm stuck because my script couldn't locate the related OU. I've tried running Get-ADOrganizationalUnit -Filter * -Properties *
and as expected I can find the OU there. But as soon as I run my script, the error message said that the OU can't be found.
I tried splitting the script into two parts, one will locate the OU, and the other will do the filtering. This is what broke my brain, the locating script worked flawlessly, and as soon as I put them back together, the script broke again and as expected, the OU is once again unavailable. Does anyone have any idea or alternative on how I should solve this, thanks a lot.
Import-Module ActiveDirectory
try {
$ouNameToMove = "VPN Users"
$searchBase = "DC=example,DC=com"
$ou = Get-ADOrganizationalUnit -Filter { Name -like $ouNameToMove } -SearchBase $searchBase
if ($ou -eq $null) {
throw "OU '$ouNameToMove' not found in Active Directory."
}
$ouDNToMove = $ou.DistinguishedName
# Filter for all users
$query = Get-ADUser -Filter * -SearchBase $searchBase -Properties distinguishedName, userAccountControl
$filteredAccounts = @()
foreach ($user in $query) {
$distinguishedName = $user.distinguishedName
$userAccountControl = $user.userAccountControl
# Check if the second CN is 'CN=Users', account is enabled, contains a dot (.), and no spaces in the distinguished name
if ($distinguishedName -match ".*,CN=([^,]+),.*" -and $Matches[1] -eq "Users" -and $userAccountControl -ne $null -and (($userAccountControl -band 2) -eq 0) -and $distinguishedName -like "*.*" -and $distinguishedName -notlike "* *") {
$filteredAccounts += $distinguishedName
}
}
if ($filteredAccounts.Count -gt 0) {
# Move accounts to the OU
foreach ($account in $filteredAccounts) {
$userCN = $account -replace "^CN=([^,]+),.*", '$1'
$newDN = "CN=$userCN,$ouDNToMove"
Set-ADUser -Identity $account -Replace @{distinguishedName = $newDN}
}
Write-Host "Accounts have been moved to the OU '$ouNameToMove' successfully."
} else {
Write-Host "No accounts found to move."
}
}
catch {
Write-Host "Error occurred: $($_.Exception.Message)"
}
As per my comment, I would suggest using a different cmdlet like Move-ADObject to accomplish your task.
# Old Code
Set-ADUser -Identity $account -Replace @{distinguishedName = $newDN}
# New Code
Move-ADObject -Identity $account -TargetPath $ouDNToMove