Creating New contacts through script


I’m failing with “New-ADObject : The object name has bad syntax” in the following script:

 foreach ($i in $contacts) {

New-ADObject -Name $i -Type Contact -Path "ou=Us-contacts,ou=ou=US,dc=corp,dc=pri" -OtherAttributes @{'mail'=@($i)} 


In $contacts variable I have few strings:


I’ve tried already to change name parameter with $($i) or “$($I)”. Also can someone please explain why sometimmes is neccessary to use $($i) instead of $i.

Kind regards,

What is the purpose of the nickname variable? I don’t see you using it anywhere else in the code.

Give this a read about sub expressions:

“The object name has bad syntax”
Looking at your script, you´re not using the variable you created on the second line (-Name $i should be -Name $nicnkame). As for the -Otherattributes hashtable, the values should probably be strings, so “$i” or “$($i)”, in this case either should work (if $i already is a string “” is not needed). In a string $() tells powershell that what´s inside is a variable or function that needs to be resolved. If $i had multiple values, and you just wanted the value for name, in a string “$” would not work. The .name would be red as a string, you would need to use “$($”.

Hello guys,

Thank you for the answers.

Actually the $nickname is for mailnickname attribute which I wanted to specify later.

But even if I run this

 New-ADObject -Name "$($i)" -Type Contact -Path "ou=Us-contacts,ou=ou=US,dc=corp,dc=pri" 

It fails with the same error.

Best regards

What version of Exchange are you running? If you are running 2016 or Exchange online, have you tried the New-MailContact cmdlet?


Another thing to try. Put your contacts in a text file and run the following code:

Get-Content C:\contacts.txt | foreach {New-Adobject -name $_ -Type Contact -Path YOUROU}

The problem was solved after I’ve copied the distinguishedname instead of typing it. Not sure if it is case sensitive but I couldn’t find a typo.

Best regards