Score:0

How to: If a user already exits, create the user with a "1" after their name -PowerShell Active Directory

ug flag

I have a script written here that checks if an AD already exists. If they do exist, then the script lets me know. If they don't, then it creates them:

    if (Get-ADUser -F { SamAccountName -eq $username }) {
        
        # If user does exist, give a warning
        Write-Warning "A user account with username $username already exists in Active Directory."
    else {

##Then it carries on here with creating the user

What I'd like to do is, if they exist, create the user with the same naming convention, but put a "1" after their name. I know this sounds silly.... but I've been asked if that is possible.

And if they don't exist, well, carry on as usual and create them :)

Any help would be appreciated ladies and gents.

Thank you :)

br flag
[1] make the call against your AD to see if there are any with that basic user name. for example - `-like 'SmithJ*'`. [2] force the result to be an array by wrapping the call in `@()`. [3] if `$Result.Count` is not zero, grab the digit suffixes, sort to find highest, increment by 1, and finally use that number to create your new user name.
Score:0
in flag

I didn't really touch the commented out parts, but hopefully this gives you an idea. I don't had an AD server handy to test it against to just be aware I can't guarantee its 100%

function validation($User){
    if (Get-ADUser -F { SamAccountName -eq $User.username }) {
        $usernumber = 1
        while (Get-ADUser -F { SamAccountName -eq ($User.username + $usernumber)}){
            $usernumber++
        }
        $NewUserName = $User.username + $usernumber
        Add_User($NewUserName, $User)
        }
        else {
            $NewUserName = $User.username
        Add_User($NewUserName, $User)
        }
}

function Add_User($Username, $User){
New-ADUser `
            -SamAccountName $Username `
            -UserPrincipalName "$Username" + "@MEtest.com" `
            -Name "$Firstname $Lastname" `
            -GivenName $User.Firstname `
            -Surname $User.Lastname `
            -Enabled $True `
            -DisplayName "$User.Lastname, $User.Firstname" `
            -Path $User.ou `
            -OfficePhone $User.telephone `
            -Title $User.jobtitle `
            -AccountPassword (convertto-securestring $Password -AsPlainText -Force) -PasswordNeverExpires:$false -ChangePasswordAtLogon:$True
}

$ADUsers = Import-Csv C:\ps\usercreation.csv

$UPN = "METest.local"

foreach ($User in $ADUsers) {
    validation($User)

        #If this user exists
        Write-Host "The user account $username is created." -ForegroundColor Cyan
        
        #Sleep time to sync for Exchange push
        #write-host Pausing for Exchange Sync....
        #start-sleep -Seconds 300
    
    #Apply licenses to users created in AD then synced to Exchange
        #Set-MsolUserLicense -UserPrincipalName $newuser.UserPrincipalName -AddLicenses UI-OF-LICENSE-HERE   
        #Set-MsolUserLicense -UserPrincipalName $newuser.UserPrincipalName -AddLicenses UI-OF-LICENSE-HERE
        
    }
}

Read-Host -Prompt "Press Enter to exit"
ug flag
Thanks! :). Unfortunately, I got this :( --> New-ADUser : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'SamAccountName'. Specified method is not supported. At line:18 char:29 + -SamAccountName $Username ` + ~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [New-ADUser], ParameterBindingException + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.ActiveDirectory.Management.Commands.NewADUser
Aalom avatar
in flag
If you just ran it and your on ISE then in the co.mand promp at the bottom type $Username and see what it returns
ug flag
It returns this: PS C:\Windows\system32> $username Mr.Wong. And that is 1 of the test usernames in my .csv file
Aalom avatar
in flag
You can probably add an out-string to it to convert from object to string. So -SamAccountName $Username ` would become -SamAccountName $Username | out-string `
ug flag
This is the error I'm getting now after replacing that -> https://i.stack.imgur.com/SXHyS.png
Aalom avatar
in flag
Its having issues with finding the username property of the csv object, is there a username column? What is the header name?
ug flag
Hi @Aalom. The headers are " FirstName | LastName | UserName | Password | JobTitle | OU | PhoneNumber
Aalom avatar
in flag
Make sure all the corresponding object properties are written case sensitive. So $User.username should be $User.UserName etc.
ug flag
I have made sure that everything matches. Just made the excel sheet all lowercase to make it simpler for testing at the moment. For some reason, still getting this https://i.stack.imgur.com/ZhPrc.png
Aalom avatar
in flag
Make sure on line 2 its $User.username if the object variable name is $User and the header is now username.
ug flag
Hi Aalom. Thank you again so much for your continued help. You have no idea how much I appreciate the assistance. I tried what you said, still the same error :(. I'll attach a screenshot of the code, the .csv and the error all in one so maybe it will make more sense to the trained eye https://i.stack.imgur.com/xD43D.png
Aalom avatar
in flag
Wait is it creating the accounts? If so what happens when you run the script again without deleting the test accounts? Does there error go away and add a 1 to usernames?
Aalom avatar
in flag
If that is the case then its returning the error, because the account does not exist in AD. But ultimately still provides a false to the comparator, and moves on. To remove the warnings use a -erroraction ignore after the } of the get-aduser statement.
Score:0
ug flag

##full script##

$ADUsers = Import-Csv C:\ps\usercreation.csv

$UPN = "METest.local"

foreach ($User in $ADUsers) {

    #Assign the data in the csv to a variable
    $username = $User.username
    $password = $User.password
    $firstname = $User.firstname
    $lastname = $User.lastname
    $OU = $User.ou #This field refers to the OU the user account is to be created in
    $telephone = $User.telephone
    $jobtitle = $User.jobtitle

    #Check and see if the user already exists in AD
    if (Get-ADUser -F { SamAccountName -eq $username }) {
        
        #Warn if the users already exists
        Write-Warning "A user account with username $username already exists in Active Directory."
    }
    else {

        #User does not exist then proceed to create the new user account
        New-ADUser `
            -SamAccountName $Username `
            -UserPrincipalName "[email protected]" `
            -Name "$Firstname $Lastname" `
            -GivenName $Firstname `
            -Surname $Lastname `
            -Enabled $True `
            -DisplayName "$Lastname, $Firstname" `
            -Path $OU `
            -OfficePhone $telephone `
            -Title $jobtitle `
            -AccountPassword (convertto-securestring $Password -AsPlainText -Force) -PasswordNeverExpires:$false -ChangePasswordAtLogon:$True

        #If this user exists
        Write-Host "The user account $username is created." -ForegroundColor Cyan
        
        #Sleep time to sync for Exchange push
        #write-host Pausing for Exchange Sync....
        #start-sleep -Seconds 300
    
    #Apply licenses to users created in AD then synced to Exchange
        #Set-MsolUserLicense -UserPrincipalName $newuser.UserPrincipalName -AddLicenses UI-OF-LICENSE-HERE   
        #Set-MsolUserLicense -UserPrincipalName $newuser.UserPrincipalName -AddLicenses UI-OF-LICENSE-HERE
        
    }
}

Read-Host -Prompt "Press Enter to exit"

P.s. dont bother about all the comments...they are there so it doesn't run certain things while I test

Score:0
in flag

Within your if statement with the warning just add

$username = $username + "1"

And then repeat the code in your else section.

Can always clean it up and place the create account code in a function and call it in each portion of the if statement.

ug flag
Hi Aalom, thanks for your reply. When I put the "$username = $username + "1" " in within the IF statement, it doesn't seem to do a great deal. It runs through the script as it should, then at the end it states WARNING: A user with username test.test1 already exists in the directory. And when I search AD, there is no one there with that name. What I need it to do is create a complete duplicate account to the one that's there, but just be "test.test1" instead of "test.test" Appreciate the help
Aalom avatar
in flag
Did you make sure to have the code execute add-aduser after changing the $username variable? Im presuming your running in some kind of loop here, if so what does it look like?
ug flag
Hey again, I'll paste my script in an answer to the script so it's easier to read
Score:0
in flag

So firstly you dont need to assign your values from The csv to variables, they are already loaded into the object and residing in memory, so you can switch out $username to $user.username repeat it for the add user section, just change the name after the period for the dataset. I think i see what happened, so if you have john doe in the system and another 2 john doe's on your list, the first time it created a john.doe1 and was succesful but the second time it failed. So you need to pull the username string trim it to the last character, do an comparison to see if the last character is a character or number. If a letter then concatenate a 1 if a number add 1 to it and concatenate that number instead. Make sense? On my phone so writing the code and researching the syntax is a pain sorry.

ug flag
Thanks for your reply. I'm going to be blatantly honest and say nope, that doesn't make much sense to me :(. Just something I've never had to mess around with so making enough sense to write it in and have it function is where I hit a wall
Aalom avatar
in flag
I'll jump on the latop in a few and try to put something together, I have had to put together an AD script before unfortunately i dont have access to the source code i wrote.
ug flag
Thank you a bunch!! P.s. Feel free to just copy and paste my script and add in what you need. I'm not fussed in the slightest.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.