Feb 22 2022 02:59 PM
Hi All,
I have a code block I am trying to get working to test if a username is already created, then move to the next. If its not existing, set variable $UPN to that username.. however, something isn't working in the test and tries to use the first option every time, even if its already an existing account. The FI and LN are provided based on content of the CSV file and that logic is not included as that does work. Any help would be greatly appreciated:
##Check for username using firstl (first name & last initial)
$SAM = "$FI$LN"
$UPN = "$Email address removed"
Write-host "Creating User $UPN" -foregroundcolor Cyan
if ($(try {get-ADUser -Identity $UPN} catch {$null}))
{ ##Check for username using flast (first initial & last name)
$SAM = "$FN$LI"
$UPN = "$SAM @ something.org"
if ($(try {get-ADUser -Identity $UPN} catch {$null}))
{ ##Check for username using fflast (first two initials & last name)
$SAM = "$FI2$LN"
$UPN = "$SAM @ something.org"
if ($(try {get-ADUser -Identity $UPN} catch {$null}))
{ ##Check for username using lastf (last name & first initial)
$SAM = "$LN$FI"
$UPN = "$SAM @ something.org"
if ($(try {get-ADUser -Identity $UPN} catch {$null}))
{ Write-host "Error - Unable to find a unique name for the account" -foregroundcolor Red
$UPN = "123454321 @ something.org"
$ID = "123454321"
}
else { Write-host "The UPN will be $UPN" -foregroundcolor Cyan
Write-output "$ID,$UPN" | out-file $BFile -append
}
}
else { Write-host "The UPN will be $UPN" -foregroundcolor Cyan
Write-output "$ID,$UPN" | out-file $BFile -append
}
}
else { Write-host "The UPN will be $UPN" -foregroundcolor Cyan
Write-output "$ID,$UPN" | out-file $BFile -append
}
}
else { Write-host "The UPN will be $UPN" -foregroundcolor Cyan
Write-output "$ID,$UPN" | out-file $BFile -append
}
Feb 23 2022 12:32 AM
@caseyj Did a script like this before, but used catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] . Don't know if that changes things?
Feb 23 2022 06:05 AM
Feb 23 2022 06:42 AM
Feb 25 2022 08:32 AM
Solution