Create bulk users in AD with a script with csv file problem !
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-04-2022 12:27 PM
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
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 :
the CSV file on my virtual server :
when i open it with note pad i have this result :
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 !
