Search code examples
powershellcsvvar

New-ADUser OtherAttributes var from CSV


I'm using the powershell script below to create new AD accounts from a CSV file. I recently added the vars for $extensionAttribute1 and $extensionAttribute2. I also added the following -OtherAttributes = @{'extensionAttribute1' = $extensionAttribute1;'extensionAttribute2'= $extensionAttribute2}

How can I correct for the following error?

New-ADUser : Cannot validate argument on parameter 'OtherAttributes'. The argument is null or an element of the argument collection contains a null value. At D:\OneDrive\Element Care\Powershell\SACRequest - Create Accounts via CSV.ps1:62 char:30 + ... -OtherAttributes @{'extensionAttribute1' = $extensionAttribute1}

ps script is as follows:

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

#Store the data from ADUsers.csv in the $ADUsers variable
$ADUsers = Import-csv "\\server\path\file.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.'First Name:'
    $Lastname   = $User.'Last Name:'
    $OU         = 'OU=CONTRACTORS,OU=ACCOUNTS,OU=organization,DC=domain,DC=lan'
    $Descritpion = $User.'Account Type'
    $company    = $User.'Employer:'
    $extensionAttribute1 = $User."Submitter Name" # The employee who originally submitted the request.
    $extensionAttribute2 = $User."Submitter email" # The email for who originally submitted the request.

   # $email      = $User.email
   # $streetaddress = $User.streetaddress
   # $city       = $User.city
   # $zipcode    = $User.zipcode
   # $state      = $User.state
   # $country    = $User.country
   # $telephone  = $User.telephone
   # $jobtitle   = $User.jobtitle
   # $department = $User.department

    #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@domain.com" `
            -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 `
            -Description $Descritpion `
            -AccountPassword (convertto-securestring $Password -AsPlainText -Force) -ChangePasswordAtLogon $True `
            -OtherAttributes @{'extensionAttribute1' = $extensionAttribute1;'extensionAttribute2'= $extensionAttribute2}
    }
    }

Solution

  • The error you recieved came IMO from the typo's you have made in the original code. Apart from that, I would advice you to use Splatting for cmdlets like New-ADUser that can have a lot of parameters. That way you keep the code both readable and maintainable, and you don't need to use the easily overlooked backtick character for line continuation.

    Provided your CSV contains all of the values and all column headers are as shown in your code, something like this should work:

    # Import active directory module for running AD cmdlets
    Import-Module ActiveDirectory
    
    #Store the data from ADUsers.csv in the $ADUsers variable
    Import-csv "\\server\path\file.csv" | ForEach-Object {
        #Check to see if the user already exists in AD
        if ((Get-ADUser -Filter "SamAccountName -eq '$($_.username)'" -ErrorAction SilentlyContinue)) {
             #If user does exist, give a warning
             Write-Warning "A user account with username $($_.username) already exist in Active Directory."
             continue
        }
        # only store these in variables as they are used in multiple properties
        $firstName = $_.'First Name:'
        $lastName  = $_.'Last Name:'
        # create a Hashtable with all properties you want to set for the new user
        $properties = @{
            'SamAccountName'        = $_.username
            'UserPrincipalName'     = '{0}@domain.com' -f $_.username
            'Name'                  = '{0} {1}' -f $firstName, $lastName
            'GivenName'             = $firstName
            'Surname'               = $lastName
            'Enabled'               = $true
            'DisplayName'           = '{0}, {1}' -f $lastName, $firstName
            'Path'                  = 'OU=CONTRACTORS,OU=ACCOUNTS,OU=organization,DC=domain,DC=lan'
            'City'                  = $_.city
            'Company'               = $_.'Employer:'
            'State'                 = $_.state
            'StreetAddress'         = $_.streetaddress
            'OfficePhone'           = $_.telephone
            'EmailAddress'          = $_.email
            'Title'                 = $_.jobtitle
            'Department'            = $_.department
            'Description'           = $_.'Account Type'
            'AccountPassword'       = (ConvertTo-SecureString $_.password -AsPlainText -Force) 
            'ChangePasswordAtLogon' = $true
            'OtherAttributes'       = @{'extensionAttribute1' = $_.'Submitter Name';'extensionAttribute2'= $_.'Submitter email'}
            # you can comment out any properties you do not need or are missing in the CSV
            # 'PostalCode'          = $_.zipcode
            # 'Country'             = $_.country
        }
        # create the new user using the properties Hashtable (splat)
        Write-Host "Creating user $($_.username)"
        New-ADUser @properties
    }