• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1342
  • Last Modified:

Pwrshell - Generate username from firstname and lastname

Hi,

I have a variable with a users firstname ($FirstName) and another variable with the users lastname ($LastName).

What I want is a new variable with a generated username.

The username should either be:
1. The first two characters from $FirstName + the first character from $LastName
2. The first character from $FirstName + the first two characters from $LastName
3. The first and third character from $FirstName + the first character from $LastName
4. The first character from $FirstName + the first and third character from $LastName
5. The first two characters from $FirstName + the second character from $LastName

I want it check up against our AD to verify that the username is not taken. If it is, it need to check username-option 2. If username-option 2 is taken, it should check for username option 3 and so on.

When it finds a free username, it should be set as $Username.

Is it possible or is there a better solution?
0
Sum Wum
Asked:
Sum Wum
1 Solution
 
Meir RivkinFull stack Software EngineerCommented:
here:

cls
$FirstName = "jonny"
$LastName = "begood"

function isUserExists($username){
	return Get-ADUser -LDAPFilter "(sAMAccountName=$username)"
}

$NameOptions = ($FirstName[0,1]+$LastName[0] -join ('')).Replace(' ',''), 
				($FirstName[0]+$LastName[0,1] -join ('')).Replace(' ',''), 
				($FirstName[0,2]+$LastName[0] -join ('')).Replace(' ',''), 
				($FirstName[0]+$LastName[0,2] -join ('')).Replace(' ',''), 
				($FirstName[0,1]+$LastName[1] -join ('')).Replace(' ','')
				
foreach ($name in $NameOptions){
	$res = isUserExists $name 
	if($res -ne $null){
		break
	}
}

#found $name 

Open in new window

0
 
QlemoC++ DeveloperCommented:
The part in lines 9 to 13 could be shortened:
# old:
  ($FirstName[0,1]+$LastName[0] -join ('')).Replace(' ','')[/b]
# new:
  -join $FirstName[0,1]+$LastName[0] -replace ' '[/b]

Open in new window

aso.
I think the check for isUserExists is wrong - it return something (not $null) if the user exists, and so the check should be reversed (-eq $null).
In addition we should also consider all suggested combinations used up already. $res will still have a value in that case after the foreach (while being $null if there is a free combination found).
0
 
Sum WumAuthor Commented:
More than perfect! Thanks!!!
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now