Creating Users with a CSV

Copper Contributor

Hi all,

 

I'm trying to create a script which will pull user's info from a .csv, check the user's DisplayName with AD to make sure a user with that DisplayName doesn't already exist, does exact same with user's SamAccountName after.

 

Once done these checks, if the user's DisplayName & SamAccountName doesn't already exist in AD it will then create the users with the info from the .csv then it will check if that user has been successfully created by checking - else, it'll say it was unsuccessful. I'm doing something similar like this with importing computers into AD too but same issue.

 

This script has worked for creating single user's but when it comes to creating multiple user's, it gets itself in a muddle.

 

I've done a lot of research and testing e.g. trying to use the 'break' but that causes the whole script to stop after the first user is detected as it's exists, trying to use 'continue' but it didn't make much difference, trying to bracket bits off, tried doing if 'false' or if 'true' after the $? wildcard, trying different operators and wildcards, using if-not and else etc but just can't seem to function properly.

 

There maybe a lot of questioning why I've done certain commands instead of other commands, a lot of this script has been me researching and testing on my lab (none of this info is genuine user's info, it's just self learning on my lab) 

 

I'm open to any command recommendations or suggestions as I mentioned, this is purely for self learning and lab purposes.

 

 

 

# Start Commands
Write-Host "STARTED SCRIPT`r`n"

# Import Active Directory Module For Running AD Cmdlets
Import-Module ActiveDirectory

# Store The Data From ADUsers.csv in THE $ADUsers variable
$filepath = Import-Csv -Path C:\Users\Administrator\Desktop\users1.csv

# Loop through each row containing user details in the csv file
ForEach ($user in ($filepath))
{

# Check if User(s) display name already exists
$ADUser = Get-AdUser -Filter {$displayname -eq $User.DisplayName}
if ($ADUser -is 'Microsoft.ActiveDirectory.Management.ADUser') {Write-Host "$displayname already exists" -ForegroundColor Red}

# Check if User(s) username already exists
$ADUser = Get-AdUser -Filter {$SamAccountName -eq $User.SamAccountName}
if ($ADUser -is 'Microsoft.ActiveDirectory.Management.ADUser') {Write-Host "$SamAccountName already exists" -ForegroundColor Red}


    # Read user data from each field in each row and assign the data to a variable as below
    $displayname = $User.'firstname' + " " + $User.'lastname'
    $firstname = $User.'firstname'
    $lastname = $User.'lastname'
    $jobtitle = $User.'jobtitle'
    $telephone = $User.'telephone'
    $department = $User.'department'
    $UPN = $User.'email'
    $SamAccountName = $User.'username'
    $EmailAddress = $User.'email'
    $Password = $User.'password'
    $OU = $User.'OU'
    
    # Create New AD Users
    New-ADUser -Name "$displayname" -DisplayName "$displayname" -GivenName "$firstname" -Surname "$lastname" -Title "$jobtitle" -OfficePhone "$telephone" -Department "$department" -UserPrincipalName "$UPN" -SamAccountName "$SamAccountName" -EmailAddress "$EmailAddress" -AccountPassword (ConvertTo-SecureString $password -AsPlainText -Force) -Enabled $true -Path "$OU" -ChangePasswordAtLogon $true -PasswordNeverExpires $false
    
    # Confirm Commands
    $? | out-null
    
    $ADUser = Get-ADUser -Filter {DisplayName -eq $displayname}
    if ($ADUser -is 'Microsoft.ActiveDirectory.Management.ADUser') {Write-Host "$displayname account was successfully created" -ForegroundColor Green}
    
    else {Write-Host "$displayname account was unsuccessfully created" -ForegroundColor Red}

    $ErrorActionPreference = 'SilentlyContinue'
    }

# Finish Commands
Write-Host "FINISHED SCRIPT`r`n"

 

 

 

This is the CSV it's pulling the info from.

 

 

firstname	lastname	jobtitle	telephone	department	username	email	password	OU
Fred	Jones	Maths Teacher	987654321	Maths	Fred.Jones	Fred.Jones@Jord.Local	Hello2021!	OU=Teaching Staff,OU=Users,OU=Test,DC=Jord,DC=Local
Fred	Try	Administrator	123456789	Admin	Fred.Try	Fred.Try@Jord.Local	Hello2021!	OU=Admin Staff,OU=Users,OU=Test,DC=Jord,DC=Local
Ren	Jones	English Teacher	134258679	English	Ren.Jones	Ren.Jones@Jord.Local	Hello2021!	OU=Customers,OU=Users,OU=Test,DC=Jord,DC=Local
Sophie	Hop	Lanuages Teacher	174392834	Languages	Sophie.Hop	Sophie.Hop@Jord.Local	Hello2021!	OU=Other,OU=Users,OU=Test,DC=Jord,DC=Local

 

 

 

 

This is the output of the script

 

 

PS C:\Users\Administrator> \\FREENAS\Network\PowerShell\Users\User Creation\Automatically\test.ps1
STARTED SCRIPT

Sophie Hop already exists
Sophie.Hop already exists
Fred Jones account was successfully created
Fred Jones already exists
Fred.Jones already exists
Fred Try account was successfully created
Fred Try already exists
Fred.Try already exists
Ren Jones account was successfully created
Ren Jones already exists
Ren.Jones already exists
Sophie Hop account was successfully created
FINISHED SCRIPT


PS C:\Users\Administrator> 

 

 

 

or even taking out this bit of script

 

 

$ADUser = Get-ADUser -Filter {DisplayName -eq $displayname}
    if ($ADUser -is 'Microsoft.ActiveDirectory.Management.ADUser') {Write-Host "$displayname account was successfully created" -ForegroundColor Green}
    
    else {Write-Host "$displayname account was unsuccessfully created" -ForegroundColor Red}

 

 

it still gets in a mess with this output (even though the AD account don't exist beforehand, they do after the script is ran though)

 

 

PS C:\Users\Administrator> \\FREENAS\Network\PowerShell\Users\User Creation\Automatically\test.ps1
STARTED SCRIPT

Sophie Hop already exists
Sophie.Hop already exists
Fred Jones already exists
Fred.Jones already exists
Fred Try already exists
Fred.Try already exists
Ren Jones already exists
Ren.Jones already exists
FINISHED SCRIPT

 

 

Any help, suggestions or recommendations are very appreciated

8 Replies

@Jord9857 

 

Hi,
Your script is correct but you are miss something:
In your csv file you doesn't have DisplayName or SamAccountName value, so you can't check if user exist or not , see line 15 of your script:

$ADUser = Get-AdUser -Filter {$displayname -eq $User.DisplayName}

 

So you have the choice, or you adding this columns in the csv with the correct value or you check if user exist with other parameters, for example firstname or lastname combined together.

 

Hope this help

@AharonBensadoun 

 

Hi,

Thank you for your response.
However even making this adjustment to the .csv, it still doesn't work properly.

 

firstname	lastname	displayname	jobtitle	telephone	department	username	SamAccountName	email	password	OU
Fred	Jones	Fred Jones	Maths Teacher	987654321	Maths	Fred.Jones	Fred.Jones	Fred.Jones@Jord.Local	Hello2021!	OU=Teaching Staff,OU=Users,OU=Test,DC=Jord,DC=Local
Fred	Try	Fred Try	Administrator	123456789	Admin	Fred.Try	Fred.Try	Fred.Try@Jord.Local	Hello2021!	OU=Admin Staff,OU=Users,OU=Test,DC=Jord,DC=Local
Ren	Jones	Ren Jones	English Teacher	134258679	English	Ren.Jones	Ren.Jones	Ren.Jones@Jord.Local	Hello2021!	OU=Customers,OU=Users,OU=Test,DC=Jord,DC=Local
Sophie	Hop	Sophie Hop	Lanuages Teacher	174392834	Languages	Sophie.Hop	Sophie.Hop	Sophie.Hop@Jord.Local	Hello2021!	OU=Other,OU=Users,OU=Test,DC=Jord,DC=Local

 

This is the first output (user's don't exist) - it works completely fine for the user Sophie Hop but same issue with the other user's 

STARTED SCRIPT

Get-AdUser : Variable: 'displayname' found in expression: $displayname is not defined.
At test.ps1:15 char:11
+ $ADUser = Get-AdUser -Filter {DisplayName -eq $displayname}
+           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-ADUser], ArgumentException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Commands.GetADUser
 
Get-AdUser : Variable: 'SamAccountName' found in expression: $SamAccountName is not defined.
At test.ps1:19 char:11
+ $ADUser = Get-AdUser -Filter {SamAccountName -eq $SamAccountName}
+           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-ADUser], ArgumentException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Commands.GetADUser
 
Fred Jones account was successfully created
Fred Jones already exists
Fred.Jones already exists
Fred Try account was successfully created
Fred Try already exists
Fred.Try already exists
Ren Jones account was successfully created
Ren Jones already exists
Ren.Jones already exists
Sophie Hop account was successfully created
FINISHED SCRIPT

 

This is the 2nd output (user's already exist)

STARTED SCRIPT

Sophie Hop already exists
Sophie.Hop already exists
Fred Jones account was successfully created
Fred Jones already exists
Fred.Jones already exists
Fred Try account was successfully created
Fred Try already exists
Fred.Try already exists
Ren Jones account was successfully created
Ren Jones already exists
Ren.Jones already exists
Sophie Hop account was successfully created
FINISHED SCRIPT

 

Hi,
You need to look at your logic a bit closer. You have IF Statements but they are not nested or
are using AND comparison to have both components match. Also you are not throwing a variable that says the user exists to provide a logic check if you actually need to create the account. Right now it runs each if statement then runs the creation statement.

I find it may help sometimes to write down in a document the logic process before tackling the coding.
So what do I need to do/change please?
Hi @Jord9857,
Are you sur your csv is comma delimited ? Because I tested your script and it's working fine for me.

Hi @AharonBensadoun 

 

Yep, tried both CSV (Comma delimited) and CSV UTF-8 (Comma delimited) but still same issue :\

@Jord9857 

I've put some additional comments in your script but as I said before write out the logic on some paper and it will help you write the correct statements.  Right now you just have a loop that applies every action to each item that goes through the script.  The if statements should have an else statement that creates the list of users you are going to act against or you will just attempt to recreate all users each time.  The creation portion of the script should only loop through the users who don't exist properly, not every user.

 

# Start Commands
Write-Host "STARTED SCRIPT`r`n"

# Import Active Directory Module For Running AD Cmdlets
Import-Module ActiveDirectory

# Store The Data From ADUsers.csv in THE $ADUsers variable
$filepath = Import-Csv -Path C:\Users\Administrator\Desktop\users1.csv

# Loop through each row containing user details in the csv file
ForEach ($user in ($filepath))
    {

    # Check if User(s) display name already exists
    $ADUser = Get-AdUser -Filter {$displayname -eq $User.DisplayName}
    if ($ADUser -is 'Microsoft.ActiveDirectory.Management.ADUser') 
        {
        Write-Host "$displayname already exists" -ForegroundColor Red
        }
#What are you going to do if the user doesn't exist? (else Statement should be here to put the Incorrects into an array to correct later right??

# Check if User(s) username already exists
    $ADUser = Get-AdUser -Filter {$SamAccountName -eq $User.SamAccountName}
    if ($ADUser -is 'Microsoft.ActiveDirectory.Management.ADUser') 
        {
        Write-Host "$SamAccountName already exists" -ForegroundColor Red
        }
#What are you going to do if the username doesn't exist? (else Statement should be here to put the Incorrects into an array to correct later right??


# Should not this section only be done for users who didn't pass the above if statement? otherwise the following commands apply to all users in the file 

    # Read user data from each field in each row and assign the data to a variable as below
    $displayname = $User.'firstname' + " " + $User.'lastname'
    $firstname = $User.'firstname'
    $lastname = $User.'lastname'
    $jobtitle = $User.'jobtitle'
    $telephone = $User.'telephone'
    $department = $User.'department'
    $UPN = $User.'email'
    $SamAccountName = $User.'username'
    $EmailAddress = $User.'email'
    $Password = $User.'password'
    $OU = $User.'OU'
    
    # Create New AD Users
    New-ADUser -Name "$displayname" -DisplayName "$displayname" -GivenName "$firstname" -Surname "$lastname" -Title "$jobtitle" -OfficePhone "$telephone" -Department "$department" -UserPrincipalName "$UPN" -SamAccountName "$SamAccountName" -EmailAddress "$EmailAddress" -AccountPassword (ConvertTo-SecureString $password -AsPlainText -Force) -Enabled $true -Path "$OU" -ChangePasswordAtLogon $true -PasswordNeverExpires $false
    
    # Confirm Commands
    $? | out-null
    
    $ADUser = Get-ADUser -Filter {DisplayName -eq $displayname}
    if ($ADUser -is 'Microsoft.ActiveDirectory.Management.ADUser') {Write-Host "$displayname account was successfully created" -ForegroundColor Green}
    
    else {Write-Host "$displayname account was unsuccessfully created" -ForegroundColor Red}

    $ErrorActionPreference = 'SilentlyContinue'
    }

# Finish Commands
Write-Host "FINISHED SCRIPT`r`n"

   

@Jord9857 

Hi Jord,

 

here's a script I did up a a while back (2019) for creating AD users if it's helpful CreateUsers.ps1 it has a CSV file for input NewUsertemplate.xlsx