While Loop with More than One Condition? Need Help.

Copper Contributor

I already have a script the automates the creation of users.  If the sAMAccountName is not unique, then My script has a while loop that Basically says

if ($user -eq $null) {

$i = 1
while (((Get-ADUser -Filter {sAMAccountName -eq $sAMAccountName}) -ne $null) {
$sAMAccountName = $sAMAccountName + $i
$i++
}
$i--

 

I recently discovered an issue, that is not addressed with this.. If the AD-Object itself, for the user is the SAME name in the same OU, the user cannot be created of course.   If they are in a different OU they can.  The other day I had 2 users with the same NAME, and even though the sams account is unique, my code doesn't address when the Object name is the same as well.  I tried this, but can't seem to get it to work:

(This finds any user in that OU path that has the SAME Object name)

 

$GetSameName = Get-ADUser -Filter * -SearchBase $path -Properties Name | Where-Object{$_.Name -and ($name -contains $_.Name)}

 

if ($user -eq $null) {

$i = 1
while (((Get-ADUser -Filter {sAMAccountName -eq $sAMAccountName}) -ne $null) -and ( $name -eq $GetSameName )) {
$sAMAccountName = $sAMAccountName + $i
$i++
}
$i--

 

However, I can't figure out how to incorporate this into my while loop. I basically want it to hit the incrementation loop,  if the sAMAccountName,  or if the Object Name is not unique in that OU. So Check the sAMAccount name, if not unique, hit the incantation look.  If the sAMSAccount name IS unique, but the ADObject Name is still not, then STILL hit some sort of incrementation loop that leaves the Unique sAMSAccount name alone, BUT increments the $name, that will be used in the Unique creation of the AD-Object.

 

1 Reply
An option for you to consider.
Maybe check that the SAMAccountName is globally unique across AD, and make the samaccountname and name properties the same for each user.