Search code examples
arrayslistobjecthashtablepowershell-3.0

Issue creating an array of objects from a csv file


I'm fairly new with Powershell, so this is likely a rookie mistake, but I am trying to take a CSV document containing only user display names, query AD for the required information, and populate that information into object properties using a hash table.

Here is what i have right now

$Path = "C:\Scripts\Generate-CSRSpreadsheets\Roster-Jpay.csv"
$Table = Import-csv -Path $Path -Header EmployeeDisplayName
$Array = @()
$ADUser = Get-ADUser -Properties DisplayName,Manager -Filter {DisplayName -eq $_.EmployeeDisplayname}


ForEach($User in $Table){

    $Object = New-Object PSObject -Property @{

        DisplayName = $ADUser.DisplayName
        GivenName   = $ADUser.GivenName
        Surname     = $ADUser.Surname
        Email       = $ADUser.Mail
    }

    $Array += $Object
}

This seems to me like it should work fine, but when I check my output it looks something like this:

Example Output Image

Let's say in this example I have 9 total users, but it's only outputting the information from the last user in the csv. I've been pouring over this code, but I can't see what's wrong with it. Any help would be appreciated.

Thank you


Solution

  • You need to move your Get-ADUser inside the loop:

    $Path = "C:\Scripts\Generate-CSRSpreadsheets\Roster-Jpay.csv"
    $Table = Import-csv -Path $Path -Header EmployeeDisplayName
    $Array = @()
    
    ForEach($User in $Table){
    
        $ADUser = Get-ADUser -Filter "DisplayName -eq '$($User.EmployeeDisplayName)'" -Properties DisplayName,Manager
    
        $Object = New-Object PSObject -Property @{
    
            DisplayName = $ADUser.DisplayName
            GivenName   = $ADUser.GivenName
            Surname     = $ADUser.Surname
            Email       = $ADUser.Mail
        }
    
        $Array += $Object
    }