I want to create a PowerShell script that adds bulk values to AD attribute aaccountRoles according to sAMAccountName.
The concept looks like this:
sAMAccountName aaccountRoles
test.user1 value1,value2,value3
test.user2 value1,value2,value3

$data = Import-Csv -Path .\file.csv -Header "sAMAccountName", "aaccountRoles"
foreach($user in $data){
Get-ADUser -Filter "sAMAccountName -eq '$($user.sAMAccountName)'" | ForEach {Set-ADUser -Identity $_.sAMAccountName -Add @{aaccountRoles="$($user.aaccountRoles)"}}
}
I have created the above script in PowerShell, but it does not seem to work.
if I save csv file like this: csv file:my csv file the above script works, but it adds only the first value for each user, whereas I have to add all values of "aaccountRoles" attribute from csv file
CodePudding user response:
Import-Csv assumes normal comma-separated values. So when it sees this:
sAMAccountName aaccountRoles
It assumes that's all one value, since there is no comma separating them. It should look like this:
sAMAccountName,aaccountRoles
However, you also have commas separating the multiple values of aaccountRoles, and you don't want it to recognize those commas as separating new rows. So enclose those entire values in quotes:
sAMAccountName,aaccountRoles
test.user1,"value1,value2,value3"
test.user2,"value1,value2,value3"
Then when assigning the values, use @{aaccountRoles = $user.aaccountRoles.Split(',')}
