cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
Bookmark
|
Subscribe
|
522
Views
0
Helpful
0
Replies

Create bulk users in AD with a script with csv file problem !

JohnyJo123
Level 1
Level 1

Hi community, 

I have a school project and i need to create a script for create many users in Active Directory on Windows Server 2022 (Virtual Machine)

My problem is when I execute the script I have this error :

(i been searching all day)

The error say : $Username is not define

JohnyJo123_0-1667588880047.png

I feel like my problem is because i don't have excel install on this virtual server so maybe the script cant really open the csv file and then find info about username password etc ... what do you think ?

(i have excel on my physical machine and i have transfer my csv file by email to my virtual server)

the CSV file that i created with excel on my physical machine :

JohnyJo123_3-1667589676437.png

the CSV file on my virtual server :

JohnyJo123_1-1667589461684.png

when i open it with note pad i have this result :

JohnyJo123_2-1667589511346.png

 

 

 

Heres the code of my script :

# Import active directory module for running AD cmdlets
Import-Module ActiveDirectory

# Store the data from bulk.csv in the $ADUsers variable
$ADUsers = Import-Csv E:\bulk1234.csv


# Loop through each row containing user details in the CSV file
foreach ($User in $ADUsers)
{

#Read user data from each field in each row and assign the data to a variable as below

$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

# Check to see if the user already exists in AD
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 {

# User does not exist then proceed to create the new user account
# Account will be created in the OU provided by the $OU variable read from the CSV file
New-ADUser `
-SamAccountName $Username `
-UserPrincipalName "$Username@$formation1.local" `
-Name "$Firstname $Lastname" `
-GivenName $Firstname `
-Surname $Lastname `
-Enabled $True `
-DisplayName "$Lastname, $Firstname" `
-Path $OU `
-AccountPassword (ConvertTo-secureString $password -AsPlainText -Force) -ChangePasswordAtLogon $True

  }
}

 

 

Thanks in advance for your help, have a great weekend !

0 Replies 0
Quick Links