21 May 2015

Find available (unique) username in Active Directory

function test{
    for($i=0; $i -le $prenume.Split(' ').Length - 1; $i++){
        for($j=0; $j -le $nume.Split(' ').Length - 1; $j++){
                $TestName = $prenume.Split(' ')[$i].Trim() + '.' + $nume.Split(' ')[$j].Trim()
                if($TestName.Length -gt 20){ $TestName = $TestName.Substring(0,20) }
                $aduser = (Get-ADUser -LDAPFilter "(SamAccountName=$TestName)")
                if(!$aduser){
                    $TestName = [System.Globalization.CultureInfo]::CurrentCulture.TextInfo.ToTitleCase($TestName.ToLower())
                    return $TestName
                }
                Clear-Variable aduser
        }
    }

    # a unique username is was not found - try by appending numbers
    $i = 0
    while(!$aduser){
            $i++
            $TestName = $nume.Split(' ')[0].Trim() + $i + '.' + $prenume.Split(' ')[0].Trim()
            if($TestName.Length -gt 20){ $TestName = $TestName.Substring(0,20) }
            $aduser = (Get-ADUser -LDAPFilter "(SamAccountName=$TestName)")
            if(!$aduser){
                $TestName = [System.Globalization.CultureInfo]::CurrentCulture.TextInfo.ToTitleCase($TestName.ToLower())
                return $TestName
            }
    }
}