Forum Discussion

muskap1390's avatar
muskap1390
Copper Contributor
Mar 12, 2023
Solved

Need help with user creation script

I'm using a script to create user accounts from a CSV file using powershell. The issue I keep running into is that the email and the principal name fields are always left blank on all the accounts an...
  • eliekarkafy's avatar
    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")
    }

Resources