My script to import AD contacts to a new domain fails because some values are Null & Empty. I exported the contacts as an XML. How do I fix this with an IF statement to create the AD Object and skip if Null & Empty, but fill it in if there is a value?
Import Script
Import-Module ActiveDirectory
$import = Import-Clixml "C:\Users\Downloads\contacts.xml"
foreach($contact in $import){
$newContact=@{
path = "OU=Test,OU=domain,OU=B"
type = "Contact"
Name = $contact.name
otherAttributes = @{
givenname = $contact.givenName
sn = $contact.sn
mail = $contact.mail
displayName = $contact.displayName
cn = $contact.cn
co = $contact.co
company = $contact.company
l = $contact.l
mailNickname = $contact.mailNickname
telephoneNumber = $contact.telephoneNumber
st = $contact.st
streetAddress = $contact.streetAddress
postalcode = $contact.postalcode
physicalDeliveryOfficeName = $contact.physicalDeliveryOfficeName
mobile = $contact.mobile
}
}
New-ADObject @newContact
}
Error
New-ADObject : Cannot validate argument on parameter 'OtherAttributes'. The argument is null or an element of the argument collection contains a null value.
At C:\Users\Documents\Scripts\contacts-import.ps1:26 char:18
New-ADObject @newContact
~~~~~~~~~~~
CategoryInfo : InvalidData: (:) [New-ADObject], ParameterBindingValidationException
FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.NewADObject
New-ADObject : Cannot validate argument on parameter 'OtherAttributes'. The argument is null or an element of the argument collection contains a null value.
At C:\Users\Documents\Scripts\contacts-import.ps1:26 char:18
New-ADObject @newContact
~~~~~~~~~~~
CategoryInfo : InvalidData: (:) [New-ADObject], ParameterBindingValidationException
FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirecto
CodePudding user response:
Build the OtherAttributes
dictionary one entry at a time, and test if a corresponding value actually exists:
# ...
Import-Module ActiveDirectory
$import = Import-Clixml "C:\Users\Downloads\contacts.xml"
$potentialAttributes = @(
'givenName'
'sn'
'mail'
'displayName'
'cn'
'co'
'company'
'l'
'mailNickname'
'telephoneNumber'
'st'
'streetAddress'
'postalcode'
'physicalDeliveryOfficeName'
'mobile'
)
foreach($contact in $import){
$newContact=@{
path = "OU=Test,OU=domain,OU=B"
type = "Contact"
Name = $contact.name
OtherAttributes = @{}
}
foreach($attributeName in $potentialAttributes){
if(-not [string]::IsNullOrEmpty($contact.$attributeName)){
$newContact['OtherAttributes'][$attributeName] = $contact.$attributeName
}
}
New-ADObject @newContact
}