locked
Import Users from csv file RRS feed

  • Question

  • Hi, I try to import users by this script, but I get an error.

                  

    *****************************************************************

    # Import active directory module for running AD cmdl

    ets
    Import-Module activedirectory

    #Store the data from ADUsers.csv in the $ADUsers variable
    $ADUsers = Import-csv C:\Users\ezehtabchi\Desktop\Users\bulk_users2.csv -Delimiter ';'

    #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
        $email      = $User.email
        $streetaddress = $User.streetaddress
        $city       = $User.city
        $zipcode    = $User.zipcode
        $state      = $User.state
        $country    = $User.country
        $telephone  = $User.telephone
        $jobtitle   = $User.jobtitle
        $company    = $User.company
        $department = $User.department
        $Password = $User.Password


    #Check to see if the user already exists in AD
    if (Get-ADUser -filter {SamAccountName -eq $Username})
    {
    #If user does exist, give a warning
    Write-Warning "A user account with username $Username already exist 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@harvey-eug.local" `
                -Name "$Firstname $Lastname" `
                -GivenName $Firstname `
                -Surname $Lastname `
                -Enabled $True `
                -DisplayName "$Lastname, $Firstname" `
                -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 $True

    }
    }






    Get-ADUser : Variable: 'Username' found in expression: $Username is not defined.
    At C:\Users\Administrator\Desktop\Users\bulk_users1.ps1:31 char:6
    +     if (Get-ADUser -filter {SamAccountName -eq $Username})
    +         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidArgument: (:) [Get-ADUser], ArgumentException
        + FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microso 
       ft.ActiveDirectory.Management.Commands.GetADUser

    ******************


    Monday, August 12, 2019 9:02 PM

Answers

  • Now run this version to see what you get:

    Import-csv C:\Users\ezehtabchi\Desktop\Users\bulk_users2.csv -Delimiter ';' |
        ForEach-Object{
    
            #Check to see if the user already exists in AD
            if (Get-ADUser -filter {SamAccountName -eq '$($_.Username)'}) {
                #If user does exist, give a warning
                Write-Warning "A user account with username $Username already exist in Active Directory."
            } else {
                Try{
                    $userprops = @{
                        SamAccountName = $_.username
                        UserPrincipalName = '{0}@harvey-eug.local' -f $_.username
                        Name = '{0}' -f $_.Firstname, $_.Lastname
                        GivenName = $_.Firstname 
                        Surname = $_.Lastname
                        Enabled = $True
                        DisplayName = '{0}' -f $_.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 = $true
                    }
                    New-ADUser @userprops -ErrorAction Stop -PassThru
                }
                Catch{
                    Write-Host $_ -Fore green
                }
        }


    \_(ツ)_/


    • Edited by jrv Tuesday, August 13, 2019 6:46 PM
    • Marked as answer by jrv Tuesday, August 20, 2019 3:58 AM
    Tuesday, August 13, 2019 5:43 PM

All replies

  • You cannot have any blank fields or records in your CSV.


    \_(ツ)_/

    Monday, August 12, 2019 9:34 PM
  • You CSV file should have a header line defining the fields, such as "username".

    Richard Mueller - MVP Enterprise Mobility (Identity and Access)

    Monday, August 12, 2019 9:38 PM
  • it does have;

    firstname,lastname,username,email,streetaddress,city,department,password,company,ou


    Monday, August 12, 2019 9:50 PM
  • I do not have any blank fields.

    Monday, August 12, 2019 9:51 PM
  • FIrst let fix your code to use PowerShell coding methods and eliminate the unnecessary variables and constructs.

    Import-csv C:\Users\ezehtabchi\Desktop\Users\bulk_users2.csv -Delimiter ';' |
        ForEach-Object{
    
            #Check to see if the user already exists in AD
            if (Get-ADUser -filter "SamAccountName -eq '$($_.Username)'") {
                Write-Warning "A user account with username $($_.Username) already exist in Active Directory."
            } else {
                $userprops = @{
                    SamAccountName = $_.username
                    UserPrincipalName = '{0}@harvey-eug.local' -f $_.username
                    Name = '{0}' -f $_.Firstname, $_.Lastname
                    GivenName = $_.Firstname 
                    Surname = $_.Lastname
                    Enabled = $true
                    DisplayName = '{0}' -f $_.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 = $true
                }
                New-ADUser @userprops
            }
        }

    Check you CSV for correct structure in all fields.  Be sure that the delimiter is correct.  If the error tells you that a field is missing then something is wrong with your file.

    Also note that your filter is was wrong.

    Also avoid unnecessary and redundant comments as they make the code harder to understand.

    Also avoid using line extender characters as they are hard to see and get lost and cause hard to detect issues.  Either "splat" or use natural syntax breaks to avoid extenders.


    \_(ツ)_/






    • Edited by jrv Tuesday, August 13, 2019 5:18 PM
    Monday, August 12, 2019 10:52 PM
  • Your example header line uses the comma as a delimiter. As noted, the error indicates that the first field was not found.

    Richard Mueller - MVP Enterprise Mobility (Identity and Access)

    Monday, August 12, 2019 11:57 PM
  • Yes - 

    I repeat my post:

    "Check you CSV for correct structure in all fields.  Be sure that the delimiter is correct.  If the error tells you that a field is missing then something is wrong with your file.

    Also note that your filter is was wrong."


    \_(ツ)_/

    Tuesday, August 13, 2019 12:14 AM
  • I modified the script and I did correct the delimiter. But I get another error.

    Also, I would like to maintain that I have windows server 2019 standard.

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

    #Store the data from ADUsers.csv in the $ADUsers variable
    $ADUsers = Import-csv C:\Users\Desktop\Users\bulk_users2.csv -Delimiter ','

    #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
        $email      = $User.email
        $telephone  = $User.telephone
        $company    = $User.company
        $department = $User.department
        $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 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@eug.local" `
                -Name "$Firstname $Lastname" `
                -GivenName $Firstname `
                -Surname $Lastname `
                -Enabled $True `
                -DisplayName "$Lastname, $Firstname" `
                -Path $OU `
                -Company $company `
                -OfficePhone $telephone `
                -EmailAddress $email `
                -Department $department `
                -AccountPassword (convertto-securestring $Password -AsPlainText -Force) -ChangePasswordAtLogon $True

    }
    }






    New-ADUser : The server is unwilling to process the request
    At C:\Users\Desktop\Users\bulk_users1.ps1:35 char:3
    +         New-ADUser `
    +         ~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (CN=Kathy ...ey-eug,DC=lacal:Strin 
       g) [New-ADUser], ADException
        + FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Mana 
       gement.Commands.NewADUser

                   
    Tuesday, August 13, 2019 4:37 PM
  • If you start with my code the whole thing will be much easier to understand and fix.  If you insist on stubbornly doing this with bad coding then you are on your own.


    \_(ツ)_/

    Tuesday, August 13, 2019 4:42 PM
  • I used your code. and I modified my csv, no null and empty. and I get this error.

     New-ADUser : Cannot validate argument on parameter 'Path'. The argument is null or 
    empty. Provide an argument that is not null or empty, and then try the command again.
    At C:\Users\ezehtabchi\Desktop\Users\bulk_users2.ps1:31 char:24
    +             New-ADUser @userprops
    +                        ~~~~~~~~~~
        + CategoryInfo          : InvalidData: (:) [New-ADUser], ParameterBindingValidat 
       ionException
        + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirec 
       tory.Management.Commands.NewADUser
    Tuesday, August 13, 2019 5:07 PM
  • There is a typo which you can see:

     Path =$OU

    Should be:

     Path =$_.OU


    \_(ツ)_/

    Tuesday, August 13, 2019 5:18 PM
  • ok, I fixed it. but I get this again. 

    New-ADUser : The server is unwilling to process the request
    At C:\Users\ezehtabchi\Desktop\Users\bulk_users2.ps1:26 char:13
    +             New-ADUser @userprops
    +             ~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (CN=Kathy,OU=Use...ey-eug,DC=lacal:Strin 
       g) [New-ADUser], ADException
        + FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Mana 
       gement.Commands.NewADUser

    Tuesday, August 13, 2019 5:27 PM
  • Now run this version to see what you get:

    Import-csv C:\Users\ezehtabchi\Desktop\Users\bulk_users2.csv -Delimiter ';' |
        ForEach-Object{
    
            #Check to see if the user already exists in AD
            if (Get-ADUser -filter {SamAccountName -eq '$($_.Username)'}) {
                #If user does exist, give a warning
                Write-Warning "A user account with username $Username already exist in Active Directory."
            } else {
                Try{
                    $userprops = @{
                        SamAccountName = $_.username
                        UserPrincipalName = '{0}@harvey-eug.local' -f $_.username
                        Name = '{0}' -f $_.Firstname, $_.Lastname
                        GivenName = $_.Firstname 
                        Surname = $_.Lastname
                        Enabled = $True
                        DisplayName = '{0}' -f $_.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 = $true
                    }
                    New-ADUser @userprops -ErrorAction Stop -PassThru
                }
                Catch{
                    Write-Host $_ -Fore green
                }
        }


    \_(ツ)_/


    • Edited by jrv Tuesday, August 13, 2019 6:46 PM
    • Marked as answer by jrv Tuesday, August 20, 2019 3:58 AM
    Tuesday, August 13, 2019 5:43 PM
  • I get this error now. :-)

    Get-ADUser : Variable: 'Username' found in expression: $Username is not defined.
    At C:\Users\ezehtabchi\Desktop\Users\bulk_users3.ps1:5 char:13
    +         if (Get-ADUser -F {SamAccountName -eq $Username})
    +             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidArgument: (:) [Get-ADUser], ArgumentException
        + FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDire 
       ctory.Management.Commands.GetADUser

    Tuesday, August 13, 2019 5:56 PM
  • It tells you the line so fix it.  It is just a typo.

    Remember I cannot test this code on your system  You need to think and read the errors and see what is happening.  I posted the code as an example that you would need to understand and learn to use.


    \_(ツ)_/

    Tuesday, August 13, 2019 6:00 PM
  • I fixed the above code.


    \_(ツ)_/

    Tuesday, August 13, 2019 6:44 PM
  • It looks like you got a bad copy since the original post had only one issue - the $OU variable.


    \_(ツ)_/

    Tuesday, August 13, 2019 6:47 PM