Forum Discussion

TechGuy1815's avatar
TechGuy1815
Copper Contributor
Sep 15, 2021

Import-CSV - Check Mail-Contact fields to see if changed and if so Set-Contact

I would like to Use my existing script to check if a Contact's fields below are different than the CSV and if they are use the CSV input to update each property on the Contact.

How would I do this?

If (Test-Path $CSVFileName) {

#Import the CSV file
$csvfile = Import-CSV $CSVFileName

#Loop through CSV file
foreach ($line in $csvfile) {

try {
#Create the mail contact
New-MailContact -domaincontroller $dc -Name $line.Name -ExternalEmailAddress $line.ExternalEmailAddress -OrganizationalUnit $OU -ErrorAction STOP
Set-Contact -domaincontroller $dc -Identity $line.Name -Department $line.Department -Title "Sales Team" -StreetAddress $line.StreetAddress -City $line.City -StateOrProvince $line.StateOrProvince -PostalCode $line.PostalCode -Office $line.Office -CountryOrRegion $line.CountryOrRegion
"$($line.Name) was created successfully." | Out-File $logfile -Append
}
catch {

$message = "A problem occured trying to create the $($line.Name) contact"
$message | Out-File $logfile -Append
Write-Warning $message
Write-Warning $_.Exception.Message
$_.Exception.Message | Out-File $logfile -Append
}

}
}

1 Reply

  • psophos's avatar
    psophos
    Copper Contributor

    TechGuy1815  Something like this:

    if (!Test-Path $CSVFileName) 
    {
        Write-Error "Cannot find $CSVFileName"
        exit(1)
    }
    
    foreach ($line in $csvfile) 
    {
        $contact = Get-Contact -domaincontroller $dc -Identity $line.Name -ErrorAction SilentlyContinue
        if($contact)
        {
            # The Contact exists, check details
            if( 
                ($contact.Department -ne $line.Department) -or 
                ($contact.Title -ne $line.Title) -or 
            )
            {
                # update ALL of the contacts details if any detail is different
                Set-Contact ...
            }
        }
        else 
        {
            # new contact
            New-MailContact ...
            Set-Contact ...
        }
    }

     

    but if the script is not run very often, or if there are not too many users listed int he file, you could try:

    if (!Test-Path $CSVFileName) 
    {
        Write-Error "Cannot find $CSVFileName"
        exit(1)
    }
    
    foreach ($line in $csvfile) 
    {
        $contact = Get-Contact -domaincontroller $dc -Identity $line.Name -ErrorAction SilentlyContinue
        if(!$contact)
        {
            # Contact does not exist, so create a new contact
            New-MailContact ...
        }
    
        # Always update the contact details cause the caontact exists now
        Set-Contact ...
    }

    In this second option you always update the contact details from the data in the file.

     

    Definitely try this in a test environment first.

     

Resources