Forum Discussion
TechGuy1815
Sep 15, 2021Copper Contributor
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?...
psophos
Sep 20, 2021Brass 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.