Hi,
I’m working on a module for managing users in our AD.
One part of the script is creating user names for new users and I have a couple of questions about the best way of doing some things.
We have two simple templates for user names. Staff is preferably lower case first name and if that’s taken we use first name plus last name initial.
The $fixedFirst variable in the snippet below is a sanitized version of the first name (changing it to lower case, removing accents and spaces and converting Swedish characters ‘äöå’ to ‘aoa’ respectively).
$samAccountName = $fixedFirst if ((Get-ADUser -Filter {sAMAccountName -eq $fixedFirst})) { Write-Warning -Message "$samAccountName används redan." $samAccountName = $fixedFirst + $fixedLast.Substring(0,1)
As you can see it attempts to set the username as $fixedFirst and if that user name already exists it uses the first name + initial combo. As of right now I have no fallback in case that name is taken. I know I could nest another if in there, where it would then ask the user to type in the desired user name. I just wonder if there could be a better and simpler way. Especially since this is already nested in an if checking for user type.
Students are another matter. The template there is the last two digits of the year they start and the two first letters of the first name and the first four letters of the last name. In a conflict (rare) we use year and three and three. The user name must always be 8 characters long.
$samAccountName = $FirstName.Substring(0,2) $samAccountName = $samAccountName + $LastName.Substring(0,4) $samAccountName = $StudentYear + $samAccountName if ((Get-ADUser -Filter {sAMAccountName -eq $samAccountName}) -or ($samAccountName.Length -lt 8)) { Write-Warning -Message "$samAccountName används redan." $samAccountName = $FirstName.Substring(0,3) $samAccountName = $samAccountName + $LastName.Substring(0,3) $samAccountName = $StudentYear + $samAccountName }
This basically does the same for students as the above does for staff. It tries the default format first and if there’s a conflict or the user name is shorter than eight characters it jumps to the three plus three format with no option for getting a name from the user.
To summarize. I wish to have a three step process where the script tests first the basic template, then if that fails it tests the backup template, and finally if that fails it should ask the user for the desired final username… and of course test that too before continuing.
I know I can nest a number of ifs, but I think there ought to be a better way of doing all this.