Tuesday, 1 October 2013

Matching users from a CSV against Active Directory using PowerShell

I am trying to match users I have in a CSV with two columns (givenName and sn) against active directory.

The following script produces no output at all, not even an error:
Import-Csv input.csv | foreach {Get-ADUser -LDAPFilter "(&(givenName=$_.givenName)(sn=$_.sn))"}

The components work individually:

  • Import-Csv input.csv
  • Get-ADUser -LDAPFilter "(&(givenName=karl)(sn=foley))"
  • Import-Csv input.csv | foreach {write-host $_.givenName,$_.sn}

I've also verified that there are no extra characters in the csv using:
Import-Csv input.csv | foreach {write-host $_.givenName,$_.givenName.length,$_.sn,$_.sn.length}

What am I doing wrong please?

1 comment:

  1. Excellent (fast) answer from Mike Laughlin over on the Technet forums. It should be:
    Import-Csv input.csv | foreach {Get-ADUser -LDAPFilter "(&(givenName=$($_.givenName))(sn=$($_.sn)))"}