Skip to content

Instantly share code, notes, and snippets.

@dotps1
Last active August 29, 2015 14:04
Show Gist options
  • Select an option

  • Save dotps1/1e0b446c8ce97d8820f9 to your computer and use it in GitHub Desktop.

Select an option

Save dotps1/1e0b446c8ce97d8820f9 to your computer and use it in GitHub Desktop.
Creates a unique AD DS Username.
<#
.SYNOPSIS
Creates a new username with AD DS Validation.
.DESCRIPTION
Create a new username with the following order until a unique Username is found.
1. First Initial Last Name.
2. First Initial First Middle Intial Last Name.
3. Itterates First Name adding Char until a unique Username is found.
.EXAMPLE
New-Username -FirstName John -LastName Doe
---OUTPUT---
jdoe
.EXAMPLE
New-Username -FirstName Jane -LastName Doe -MiddleName Ala
---OUTPUT---
jadoe
.NOTES
Requires ActiveDirectory Module available with Remote Server Administration Tools.
RSAT 7SP1: http://www.microsoft.com/en-us/download/details.aspx?id=7887
RSAT 8: http://www.microsoft.com/en-us/download/details.aspx?id=28972
RSAT 8.1: http://www.microsoft.com/en-us/download/details.aspx?id=39296
.LINK
http://dotps1.github.io
#>
function New-Username
{
[CmdletBinding()]
[OutputType([String])]
param
(
# FirstName, Type String, The first name of the user to be created.
[Parameter(Mandatory = $true)]
[String]
$FirstName,
# LastName, Type String, the last name of the user to be created.
[Parameter(Mandatory = $true)]
[String]
$LastName,
# MiddleName, Type String, the middle name of the user to be created.
[Parameter(Mandatory = $false)]
[AllowNull()]
[String]
$MiddleName
)
Begin
{
if (-not(Get-Module -Name ActiveDirectory))
{
try
{
Import-Module -Name ActiveDirectory -ErrorAction Stop
}
catch
{
throw "ActiveDirectory Module is not available on this computer, and this cmdlet cannot be used. Use Get-Help New-Username -Full and see the .NOTE section for links about RSAT."
}
}
# '|' = Or Operand, '\s' = Spaces, '-' = Hyphens, ''' = Apostrophe,
[RegEx]$pattern = "\s|-|'"
}
Process
{
try
{
$primaryUsername = ($FirstName.Substring(0,1) + $LastName) -replace $pattern,""
Get-ADUser -Identity $primaryUsername | Out-Null
}
catch
{
return $primaryUsername.ToLower()
}
if (-not([String]::IsNullOrEmpty($MiddleName)))
{
try
{
$secondaryUsername = ($FirstName.Substring(0,1) + $MiddleName.Substring(0,1) + $LastName) -replace $pattern,""
Get-ADUser -Identity $secondaryUsername | Out-Null
}
catch
{
return $secondaryUsername.ToLower()
}
}
foreach ($char in $FirstName.ToCharArray())
{
$prefix += $char
$tertiaryUsername = ($prefix + $LastName) -replace $pattern,""
if ($tertiaryUsername -eq $primaryUsername)
{
continue
}
try
{
Get-ADUser -Identity $tertiaryUsername | Out-Null
}
catch
{
return $tertiaryUsername.ToLower()
break
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment