lotirthos227
lotirthos227

Reputation: 327

User creation script avoid duplicate username

I would like to do an Active Directory search using PowerShell to discover if the username I want to create is already in use,. If it is already in use I want the script to add the following number at the and of the user name.

Import-Module ActiveDirectory
    $family= Mclaren
    $first= Tony
    #This part of the script will use the first 5 letters of $family and the first 2 letters of $first and join them together to give the $username of 7 letters
    $username = $family.Substring(0, [math]::Min(5, $family.Length)) + $first.Substring(0, [math]::Min(2, $first.Length)) 

Upvotes: 0

Views: 4511

Answers (1)

David Martin
David Martin

Reputation: 12248

I think this will get you close, it uses the ActiveDirectory module.

Import-Module ActiveDirectory

$family = "Mclaren*"

# Get users matching the search criteria
$MatchingUsers = Get-ADUser -Filter 'UserPrincipalName -like $family' 

if ($MatchingUsers)
{
    # Get an array of usernames by splitting on the @ symbol
    $MatchingUsers = $MatchingUsers | Select -expandProperty UserPrincipalName | %{($_ -split "@")[0]}

    # loop around each user extracting just the numeric part
    $userNumbers = @()
    $MatchingUsers | % { 
        if ($_ -match '\d+')
        {
            $userNumbers += $matches[0]
        }
    }

    # Find the maximum number
    $maxUserNumber = ($userNumbers | Measure-Object -max).Maximum

    # Store the result adding one along the way (probably worth double checking it doesn't exist)
    $suggestedUserName = $family$($maxUserNumber+1)
}
else
{
    # no matches so just use the name
    $suggestedUserName = $family
}

# Display the results
Write-Host $suggestedUserName

Upvotes: 2

Related Questions