Forum Discussion
Need help with user creation script
- Mar 13, 2023
Please try the below code and let me know if its works for you. you add the write host if needed. please note that this script move your user to the corresponding OU specified in the CSV file as well
# Replace with the path to your CSV file
$csvPath = "C:\users.csv"
# Read the CSV file
$users = Import-Csv $csvPath
# Loop through each user in the CSV file
foreach ($user in $users) {
# Get the values from the CSV file
$username = $user.Username
$password = $user.Password
$firstname = $user.Firstname
$lastname = $user.Lastname
$email = $user.Email
$ou = $user.OU
# Create the new user object
$newUser = New-Object -TypeName System.DirectoryServices.AccountManagement.UserPrincipal([System.DirectoryServices.AccountManagement.PrincipalContext]::Domain)
$newUser.Name = "$firstname $lastname"
$newUser.DisplayName = "$firstname $lastname"
$newUser.UserPrincipalName = "$email address removed for privacy reasons""
$newUser.SamAccountName = $username
$newUser.SetPassword($password)
$newUser.Enabled = $true
$newUser.EmailAddress = $email
$newUser.Save()
# Move the user to the specified OU
$newUser = [ADSI]("LDAP://" + $newUser.DistinguishedName)
$newUser.psbase.MoveTo("LDAP://$ou")
}
Please try the below code and let me know if its works for you. you add the write host if needed. please note that this script move your user to the corresponding OU specified in the CSV file as well
# Replace with the path to your CSV file
$csvPath = "C:\users.csv"
# Read the CSV file
$users = Import-Csv $csvPath
# Loop through each user in the CSV file
foreach ($user in $users) {
# Get the values from the CSV file
$username = $user.Username
$password = $user.Password
$firstname = $user.Firstname
$lastname = $user.Lastname
$email = $user.Email
$ou = $user.OU
# Create the new user object
$newUser = New-Object -TypeName System.DirectoryServices.AccountManagement.UserPrincipal([System.DirectoryServices.AccountManagement.PrincipalContext]::Domain)
$newUser.Name = "$firstname $lastname"
$newUser.DisplayName = "$firstname $lastname"
$newUser.UserPrincipalName = "$email address removed for privacy reasons""
$newUser.SamAccountName = $username
$newUser.SetPassword($password)
$newUser.Enabled = $true
$newUser.EmailAddress = $email
$newUser.Save()
# Move the user to the specified OU
$newUser = [ADSI]("LDAP://" + $newUser.DistinguishedName)
$newUser.psbase.MoveTo("LDAP://$ou")
}