Skip to content

Instantly share code, notes, and snippets.

@jeremytbrun
Created February 26, 2019 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeremytbrun/04c41fe0d7aad01de291430cefb2593b to your computer and use it in GitHub Desktop.
Save jeremytbrun/04c41fe0d7aad01de291430cefb2593b to your computer and use it in GitHub Desktop.
Get-UniqueSamAccountNames
$Items = Import-Csv '.\data.csv'
$Items | ForEach-Object {
#Init our flag for a unique username
$Unique = $false
#Init our target SamAccountName
$Target_SamAccountName = $_.SamAccountName
#Init Regex pattern
$Pattern = "^$Target_SamAccountName\d*"
#Get all existing accounts that have the same SamAccountName regardless of numeric suffix
$ExistingItems = @(Get-ADUser -Filter "SamAccountName -like '$Target_SamAccountName*'" | Where-Object {$_.SamAccountName -match $Pattern} | Select-Object -ExpandProperty SamAccountName)
if ($ExistingItems -notcontains $Target_SamAccountName) { #Found unique on first try
$Unique = $true
}
else { #Have to search for next available unique numeric suffix
#Init our numeric suffix
$Numeric = 1
while (-not $Unique) {
if($ExistingItems -notcontains "$Target_SamAccountName$Numeric") { #Found next available numeric suffix
$Unique = $true
$Target_SamAccountName = "$Target_SamAccountName$Numeric"
}
else { #Try next
$Numeric++
}
}
}
# Log the info/create an account, etc...
Write-Host $Target_SamAccountName
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment