Import-Csv (DisplayName) Get-ADUser

I have tried two different ways of pulling properties for ADUsers via DisplayName but not successful

$User = Import-Csv .\Users.csv

#method 1
Foreach($psitem in $User){
    Get-ADUser -Identity "$psitem" -Properties *| Select LocationCode,SamAccountName,LastLogonDate,EmployeeStatus,EmailAddress,Manager|
        Export-Csv Users.csv -NoTypeInformation
}

#method 2
ForEach-Object {
    Get-ADUser -Identity $_.DisplayName -Properties * | Select LocationCode,SamAccountName,LastLogonDate,EmployeeStatus,EmailAddress,Manager|
       Export-Csv Users.csv -NoTypeInformation
}

My header is set correctly and I do have values in $User

How do I get these properties for each of these Users?

JT,

you cannot use the AD attribute DisplayName as the value for the paramter -Identity. You have to use the parameter -Filter then. Assumed your header in your CSV file is named “DisplayName” you could do it like this:

$UserList = Import-Csv .\Users.csv
$Result = 
Foreach ($user in $UserList) {
    Get-ADUser -Filter "DisplayName -eq '$($User.DisplayName)'" -Properties LocationCode, LastLogonDate, EmployeeStatus, EmailAddress, Manager  | Select-Object LocationCode, SamAccountName, LastLogonDate, EmployeeStatus, EmailAddress, Manager 
}
$Result |
    Export-Csv UsersOutput.csv -NoTypeInformation

… untested because I don’t have an AD to test at the moment. :wink:

If you want to use the parameter -Identity what might be a little more precise because it uses unique identifiers you have to use one of the following AD attributes:

  • A distinguished name
  • A GUID (objectGUID)
  • A security identifier (objectSid)
  • A SAM account name (sAMAccountName)

Edit:
… and I almost forgot - you should not use $PSItem for own variables as it is a reserved variable from PowerShell. It is equivalent to $_.

Edit #2:
… Doug is right. Changed the code above for future visitors. :wink:

2 Likes

Thanks Olaf, while I don’t get an error, I also get no results back. I do know those Users exist

You need to enclose it in a subexpression

“DisplayName -eq ‘$($user.displayname)’”

Beware if you copy paste my code you should manually retype the quotes

2 Likes

Thanks both for the help today