I HAVE GOT A TASK TO CREATE AROUND 150 USERS IN MY COMPANY USING POWERSHELL SCRIPT. I AM TESTING THE SCRIPT WITH 1 USER AND WHEN THE SCRIPT RUNS USER IS CREATED AND ABLE TO LOGIN ALSO. BUT SHOWING THE BELOW ERROR. I AM NOT CONFIDENT TO CREATE 150 USERS WITH THAT ERROR. PLS HELP ME. BELOW IS THE CODE AND ERROR. I WANT THESE OPTIONS ALSO...
CannotChangePassword $True
-PasswordNeverExpires $True
THE ERROR :
PS C:\Users\Administrator.UBS\Desktop> .\user.ps1
Get-ADUser: Variable: 'Username' found in expression: $Username is not defined.
#Store the data from Users.csv in the $Users variable
$Users = Import-csv C:\Users\administrator.UBS\Desktop\bulk.csv
#Loop through each row containing user details in the CSV file
foreach ($User in $Users)
{
#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
$Password = $User.Password
#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 exist."
}
else
{
#User does not exist then create the new user account
#Account will be created in the OU provided by the $OU variable read from the CSV file
$NewUser = New-ADUser `
-SamAccountName $Username `
-UserPrincipalName "$******@ubs.com" `
-Name "$Firstname $Lastname" `
-GivenName $Firstname `
-Surname $Lastname `
-Enabled $True `
-DisplayName "$Firstname$Lastname" `
-Path $OU `
-City $city `
-Company $company `
-State $state `
-StreetAddress $streetaddress `
-OfficePhone $telephone `
-EmailAddress $email `
-Title $jobtitle `
-Department $department `
-AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force)
#-ChangePasswordAtLogon $False
}
# Check if the user was successfully created
if ($NewUser)
{
# Set properties after user creation
Set-AdUser
-Identity $NewUser.SamAccountName
-CannotChangePassword $True
-PasswordNeverExpires $True
else
{
# Log an error message and continue to the next user
Write-Warning "Failed to create user account for $($User.username)."
}
}
}