Check UserName in AD

Hi Experrts,

I have a requirement to find the number of users with the same name in our AD and propose a unique name for the new user that would be created. Unfortunately i could only use the UPN since thats the only AD attribute with the user's full name. For some reason i am not getting the desired result from the below script. Can someone please help me out. this would need to say ProposedName is Can someone point out where i am wrong and how could i correct them.

# Get the preferred/desired name and the existing variants in use
$desiredName = ""
$existingNames = ",,"

$DomainSFX = ''
$desiredUPN = $desiredName.Trim($DomainSFX)
$existingUPN = $existingNames.Trim($DomainSFX)

# Parse the existing names and extract a list of indexes in use, e.g. 1,2,3
$existingIndexList = $existingUPN -split "," | ForEach-Object {$_.trim() -replace $desiredUPN,"" } | Where-Object {$_ -match "^\d+$"} | ForEach-Object {[int]$_}

# Determine the highest index in use by sorting
$lastIndex = $existingIndexList | Sort-Object | Select-Object -Last 1

# Increment to get next index and use this to create a proposed unique username
$availableIndex = $lastIndex + 2
$proposedName = $desiredUPN + $availableIndex