Home > Software engineering >  Powershell Pass .csv values to set-ADuser cmdlet
Powershell Pass .csv values to set-ADuser cmdlet

Time:05-02

I'm trying to populate extensionAttribute1 for users based on a .csv file that contain samAccoutName and ExtensionAttribute1 columns.

Bellow is the code I'm using for this:

Import-Module ActiveDirectory
$Attribcsv=Import-csv “D:\Exports\sales.csv”
ForEach ($User in $Attribcsv)
{
Get-ADUser -Identity $User.samAccountName | set-ADUser -add @{extensionAttribute1=$User.extensionAttribute1}
}

After running the code I'm receiving this error:

set-ADUser : Multiple values were specified for an attribute that can have only one value

.csv file sample:

csv

Can someone tell me what I am missing please?

Thanks

CodePudding user response:

You need to embed $User.extensionAttribute1 in a subexpression $() so the value gets expanded.

Also I would recommend adding a test to see if you can find the user before trying to set its property:

Import-Module ActiveDirectory

$Attribcsv = Import-csv 'D:\Exports\sales.csv'
foreach ($User in $Attribcsv) {
    $adUser = Get-ADUser -Identity $User.samAccountName -ErrorAction SilentlyContinue
    if ($adUser) {
        $adUser | Set-ADUser -Add @{extensionAttribute1 = $($User.extensionAttribute1)}
    }
    else {
        Write-Warning "No user with SamAccountName '$($User.samAccountName)' found.."
    }
}
  • Related