PowerShell Tip: Creating New AD User


Summary

 This TechNet Wiki is about the below Forum Post New-ADUser : The name provided is not a properly formed account name


Code Used

param ($csvFileLocation, $organizationUnit, $defaultPassword, $fqdn)

$csvFile = Import-Csv $csvFileLocation

function Create-UserName($givenName, $surName) {
    $firstPartInUserName = $givenName.Trim()
    $lastPartInUserName = $surName.Trim()

    return [string]::Format("{0}.{1}", $firstPartInUserName, $surName)
}

function Get-GivenName($displayName) {
    $firstNamePart = $displayName.Split('.')[0]

    return $firstNamePart.SubString(0, $firstNamePart.Length - 1).Trim()
}

function Get-Initials($displayName) {
    $indexOfDot = $displayName.IndexOf('.')

    return $displayName
}

function Get-LastName($displayName) {
    return $displayName.Split('.')[1].Trim()
}

foreach ($row in $csvFile) {
    $surName = $(Get-Lastname -displayName $row.displayName)
    $givenName = $(Get-GivenName -displayName $row.displayName)
    $userName = $(Create-UserName -givenName $($givenName.Trim().Replace(' ', '')) -surName $($surName.Replace(' ', '')))

    New-ADUser -SamAccountName $userName `
        -UserPrincipalName $([string]::Format("{0}@{1}", $userName, $fqdn)) -DisplayName $row.displayName -Name $([string]::Format("{0} {1}", $givenName, $surName)) `
        -Surname $surName -GivenName $givenName -Initials `
        -Department $row.department -Title $row.title -Path $organizationUnit `
        -AccountPassword $(ConvertTo-SecureString -AsPlainText $defaultPassword -Force) `
        -OfficePhone $row.officePhone -HomePhone $row.homePhone -MobilePhone $row.mobilePhone -ChangePasswordAtLogon $true `
        -Enabled $true
}

   


Error

 New-ADUser : The name provided is not a properly formed account name


Reason

 Active Directory Will not the below characters and account name should not be more than 20 characters. It should be unique

" [ ] : ; | = + * ? < > / \ ,

Solution

function Create-UserName($givenName, $surName) {
    $firstPartInUserName = $givenName.Trim()
    $lastPartInUserName = $surName.Trim()

    $returnValue = [string]::Format("{0}.{1}", $firstPartInUserName, $surName)
    
    if ($returnValue.Length -ge 20) {
        return $returnValue.Substring(0, 20)
    }

    else {
        return $returnValue
    }
}

Thanks to Richard Mueller and Mike 


See Also