Update/Add Email Addresses to Active Directory from a file using PowerShell

At my work we had an issue where several hundred users did not have email addresses set in their Active Directory accounts. I was given the task to fix that. I had access to database from which I gathered the users' missing email addresses and exported it to a csv file with the format: SAMAccountName,email address. I then created a PowerShell script that assigned users email addresses based off that CSV file. This is the PowerShell script I wrote to accomplish this. I hope that you may find it useful in helping you on whatever similar issue you may have.

Import-Module ActiveDirectory

# Get number of users who do not have email addresses
Get-ADUser -LDAPFilter '(!mail=*)' | measure | select count

# Read through email.csv and assign users' their email addresses.
$data = Get-Content emails.csv
foreach($line in $data) {
    $parts = $line.Split(',')
    $user = @{ SAM=$parts[0]; EMAIL=$parts[1] }
    try{
        Set-ADUser -Identity $user.SAM -EmailAddress $user.EMAIL
        Write-Host ("Added Email to " + $_.SAM + " successfully")
    } catch {
       Write-Host ("Error Adding Email For User: " + $user.SAM) -ForegroundColor Red
    }
}

# Get count of users with no email
Get-ADUser -LDAPFilter '(!mail=*)' | measure | select count

This is how to do the same thing using PowerShell piping:

Get-Content emails.csv | % { $p=$_.Split(','); @{SAM=$p[0]; EMAIL=$p[1]} } | % { try {Set-ADUser -Identity $_.SAM -EmailAddress $_.EMAIL; Write-Host ("Added Email to " + $_.SAM + " successfully") } catch {Write-Host ("Error Adding Email") -ForegroundColor Red} }