You don't need all that.
Updated to include csv export.
$users = Import-Csv -path "C:\Users\Administrator\Desktop\Bulkload\Input.csv"
$resultsArray = @()
foreach ($user in $users) {
$firstname = $user.FirstName
$lastname = $user.LastName
$i = 1 # pointer for first name
$LogonNameCounter = 0
$LogonNameSuffix = "" # no trailing number while looping thru first name
While($true) {
$logonname = $firstname.substring(0, $i) + $lastname + $LogonNameSuffix
"Looking for $logonname"
# Call AD here
If ($(Get-ADUser -Filter {SamAccountName -eq $logonname})) {
"That account exists."
"Try the next name."
} else {
"That account does not exist."
" Use this name. Add it to the results."
$resultsArray += [PSCustomObject]@{
FirstName=$user.FirstName;
LastName=$user.LastName
samAccountname=$logonname
}
break # exit this loop. Maybe set a flag to indicate that how to proceed.
}
if ($i -eq $firstname.Length) {
$logonNameCounter++
$LogonNameSuffix = $logonNameCounter
} else {
$i++
}
if ($logonNameCounter -gt 10) {
"We exceeded the max number to use. Something is wrong."
break # exit the while loop
}
}
"Done with this user."
}
$resultsArray | Export-Csv "C:\Users\Administrator\Desktop\Bulkload\Output-Result.csv"