Powershell script to compare .CSV file to AD. Export all the active and inactive emails in seperate .csv files.

Renu Murali 21 Reputation points
2021-08-30T11:58:48.517+00:00

I have a .csv file with the column names "Display Name, Email Address and SameAccountName". I want to compare this .csv file to active directory. So essentially, if any emails under "EmailAddress" from the .csv file does not match the "EmailAddress" from AD, I want to export the names that does not match into a separate .csv file named "inactiveusers.csv".
My script :

$csv=Import-Csv -Path C:\Users\renu\Desktop\renu\ALLUserMain30082021.csv  
$ad = Get-ADUser -Filter "Enabled -eq 'True'" -SearchBase 'OU=example,DC=example,DC=example,DC=example'  
Compare-Object -ReferenceObject $csv.EmailAddress -DifferenceObject $ad.EmailAddress -IncludeEqual -ExcludeDifferent | Select-Object -Property InputObject | Export-Csv -Path C:\Users\renu\Desktop\renu\match.csv -NoTypeInformation  
Compare-Object -ReferenceObject $csv.EmailAddress -DifferenceObject $ad.EmailAddress | Select-Object -Property InputObject | Export-Csv -Path C:\Users\renu\Desktop\renu\notmatchusers.csv -NoTypeInformation  
      

When i run the code i get the following error message.127568-error.png

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Rich Matheisen 48,026 Reputation points
    2021-08-30T15:11:28.94+00:00

    I don't see why you're encountering that error unless there are no enabled users in the organizational unit.

    Run this to verify that you get the expected results:

    $c = @"
    EmailAddress
    ******@z.com
    ******@z.com
    ******@z.com
    "@
    $csv = $c | ConvertFrom-Csv
    
    $a = @"
    Name,EmailAddress
    Adam,******@z.com
    Beth,******@z.com
    Carol,******@z.com
    Doug,******@z.com
    "@
    $ad = $a | ConvertFrom-Csv
    
    Compare-Object -ReferenceObject $csv.EmailAddress -DifferenceObject $ad.EmailAddress -IncludeEqual -ExcludeDifferent |
        Select-Object -Property InputObject |
            Export-Csv -Path C:\junk\match.csv -NoTypeInformation
    
    Compare-Object -ReferenceObject $csv.EmailAddress -DifferenceObject $ad.EmailAddress |
        Select-Object -Property InputObject |
            Export-Csv -Path C:\junk\notmatchusers.csv -NoTypeInformation
    
    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.