Hey guys,

i’m new to powershell …
I created this script by merging some found on this site to massively import some data into my Active Directory

Import-Module ActiveDirectory           
$users = Import-Csv -Path C:\users.csv                     
foreach ($user in $users) 
{Get-ADUser -Filter "SamAccountName -eq '$($user.samaccountname)'" | Set-ADUser -Office $($user.physicalDeliveryOfficeName) -StreetAddress $($User.streetAddress) -state $($User.state) -PostalCode $($User.postalCode) -city $($User.city) -Country $($User.country) -title $($User.title) -OfficePhone $($User.telephoneNumber) -MobilePhone $($User.mobile)}

from a csv file, like this:

sAMAccountName,physicalDeliveryOfficeName,streetAddress,state,postalCode,city,country,title,telephoneNumber,mobile
user1,Roma,Piazza San Pietro,Roma,12234,Roma,IT,Applications Engineer,+39 0123 111111,
user2,Roma,Piazza San Pietro,Roma,12234,Roma,IT,Specialist,+39 0123 222222,+39 555 7654321

when I import a user with all the fields populated this is imported correctly (for example the user user2 in the csv) while if I import a user who is missing a field, for example the user1 (the mobile field is missing) I get this error:

Set-ADUser : replace
in line 4 character 70

I don’t understand how to fix the problem.

2 Spice ups

fields in the CSV can’t be blank, if they are, you have to address that in your code.

You’re getting that error because you’re trying to set the parameter to a value that doesn’t exist. If there is no mobile phone number in the csv record then the -MobilePhone parameter in the Set-ADUser call will get no value.

You could try adding another loop at the beginning of the main loop that checks each column in the current csv record for a value and inserts a default value if necessary. That way you can guarantee there’s a value for every parameter in the Set-ADUser call.

1 Spice up

As above plus if it’s blank, leave it out of the set-aduser statement.
This means constructing the statement on the fly for each row.

2 Spice ups