Checking CSV Against Active Directory Users

I’ve written before on how to update Active Directory from a CSV. This time, I’ve got a CSV list of users that I want to check are valid users against my Active Directory (AD) environment.

There’s a huge amount of ways this can be done, and this is just one of them. If you have others, or ways to improve this I’m always keen to hear!

This script assumes you have a CSV file with the header (first line) with the word ‘users’. Here’s an example CSV file: myusers.csv

Below is the PowerShell script I wrote. I’ve also written about ‘If’ and ‘Else’ before, so read that if you want some clarification. The user list I have is based on User Principal Name (UPN) rather than just username, so I’m searching AD to see if there’s a match or not.

Import-Module ActiveDirectory

$Data = Import-Csv myusers.csv

foreach ($user in $data){
$upn = $user.user
$check = $(try {get-aduser -filter "userprincipalname -eq '$upn'"} catch {$null})
if ($check -ne $null) { }
else { "$upn Doesn't Exist" }
}

What I’m doing here is setting each line of the CSV as the $UPN variable to search for. Then using the ‘Try‘ function, I’m catching if there is no result/match (null). If there’s a match, it won’t equal null, so display nothing. Else, show the UPN via the $UPN variable and follow that with ‘Doesn’t Exit’.

This way, I will only get results back from each AD search where the UPN in the CSV doesn’t match a user’s UPN in my AD environment – and I get to see what those results are.

This script method can be applied in many different ways of course, but it was the first time I’d used the Try function, and it worked really well.

 

7 thoughts on “Checking CSV Against Active Directory Users

  1. Hi Adam,
    With the csv you’ve provided I believe the code needs changing to ‘$upn = $user.users’ (missing the end s).
    As you mention there are many ways to do this, my preference would be;

    $data = Import-Csv myusers.csv
    foreach ($user in $data)
    {
    $upn = $user.users
    if (!(Get-ADUser -Filter {UserPrincipalName -eq $upn}))
    {
    Write-Output “$upn doesn’t exist”
    }
    }

    Regards,
    Steve

    1. With tabs;
      $data = Import-Csv myusers.csv
      foreach ($user in $data)
      {
      $upn = $user.users
      if (!(Get-ADUser -Filter {UserPrincipalName -eq $upn}))
      {
      Write-Output “$upn doesn’t exist”
      }
      }

    2. Nice pickup, I’ll fix that. My original script was against a CSV that had the first field as user rather than users and I obviously missed changing that over! Thanks for commenting to let me know.

    1. Hi Boris,
      Thanks for that – change $users.user to $user.user – updated the original post too.
      Please let me know how that goes!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.