soMuch2Learn
soMuch2Learn

Reputation: 187

check for samaccount name, if exists, add next letter of first name, check again - recursive

Looking to build an account creation app/script [scope undecided atm] and not sure how to handle the samaccountname if it exists already. What I want to happen is, if, say, john smith already has a same account name of jsmith and jane smith is being created, that jsmith is detected, then the script checks for jasmith, if it exists, it will go to jansmith and so on.

I have not even attempted to try this string manipulation as I really do not have an idea where to start.

Thanks, JCGee

Upvotes: 0

Views: 1094

Answers (2)

wruckie
wruckie

Reputation: 1803

I had much the same issue, but i did not want any powershell dependencies

Here is my more traditional C# that I used to create AD users. Search UserPrincipal to learn more.

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainName + ":389");
        string FirstName = "Jane";
        string LastName = "Smith";

        for (int i = 1; i <= FirstName.Length; i++)
        {
            string username = LastName + FirstName.Remove(i);
            UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, username);
            if ((object)user == null) //user doesn't exists
            {
                #region Add User
                try
                {
                    UserPrincipal userex = new UserPrincipal(ctx, username, password, true);
                    userex.GivenName = firstname;
                    userex.Surname = lastname;
                    userex.DisplayName = firstname + " " + lastname;
                    userex.ExpirePasswordNow();
                    userex.Description = _UserDescr;
                    userex.Save();
                    break;
                }
                catch
                {
                    //
                }
                #endregion
            }
        }

Upvotes: 1

user189198
user189198

Reputation:

$FirstName = 'Jane';
$LastName = 'Smith';

for ($i = 1; $i -le $FirstName.Length; $i++) {
    $Account = $null;
    $Identity = $FirstName.Substring(0,$i) + $LastName;
    $Account = Get-ADUser -Identity $Identity;
    if ($Account -eq $null) {
        New-ADUser -SamAccountName $Identity -Name $Identity;
        break;
    };
}

Upvotes: 1

Related Questions