$originalCsvFile='C:\Users\rambo\Desktop\Usernames.csv'
$newCsvFile='C:\Users\rambo\Desktop\Usernames-processed.csv'

function checkUsernameCollisions($originalCsv,$newCsv){
  $csvContents=import-csv $originalCsv
  write-host "Pulling existing records from Active Directory of $env:USERDNSDOMAIN..."
  $allExistingUsers=get-aduser -Filter * -property SamAccountName,GivenName,sn,EmailAddress,Department,Description,telephoneNumber,Title,Manager,ManagedBy,City,State,postalCode,Enabled

  write-host "First pass: newSamAccountName"
  $firstPass=@()
  $count=$csvContents.count
  $itemIndex=0
  foreach ($row in $csvContents){
    $samAccountName=.{
      $principleName=$row.'User principal name'
      return [regex]::match($principleName,'^(.*)\@').captures.groups[1].value
    }
    $firstName=$row.'First name'
    $lastName=$row.'Last name'
    $itemIndex++
    write-host "Processing $itemIndex of $count`: $samAccountName..."  
    $newSamAccountName=.{
      # Default if there are not duplicating records
      $matchedSam=$allExistingUsers|?{$_.SamAccountName -eq $samAccountName}
      if(!$matchedSam){
        return $samAccountName
      }
      # Method 1: testing firstname initials + lastname combinations
      for ($i=0;$i -lt $firstName.length;$i++){
        $testUsername=($firstName[0..$i] -join '')+$lastName
        if($testUserName -notin $allExistingUsers.SamAccountName){
          return $testUsername
        }
      }
      # Method 2: incrementing the username by a single digit
      for($i=1;$i -lt 11;$i++){
        $testUsername2=$samAccountName+$i
        if($testUserName2 -notin $allExistingUsers.SamAccountName){
          return $testUsername2
        }
      }
    }
    if($newSamAccountName -ne $samAccountName){
      write-host "SAM in CSV $samAccountName shall be updated as $newSamAccountName"
    }  
    $firstPass+=$row|select-object *,@{Name='newSamAccountName';Expression={$newSamAccountName}}
  }

  $newCsvContents=$firstPass
  $conflictingUserNames=$newCsvContents|?{$_.SamAccountName -ne $_.newSamAccountName}
  write-host "There are $($conflictingUsernames.count) usernames that have conflicted with existing accounts in Active Directory. Hence, new account usernames would be modified to mitigate collisions."
  if(test-path $newCsv){remove-item $newCsv -force}
  if(!(test-path $(split-path $newCsv -parent))){mkdir $(split-path $newCsv -parent) -force}
  $oldHeaders='"'+$($csvContents[0].psobject.Properties.Name -join '","')+'"'
  $newHeaders=$oldHeaders+',"newSamAccountName"'
  Add-Content -Path $newCsv -Value $newHeaders
  $newCsvContents|Export-Csv $newCsv -NoTypeInformation -append
}

checkUsernameCollisions $originalCsvFile $newCsvFile