Search code examples
wpfpowershell

How to display a Powershell output array in a list box


Trying to figure out how to get powershell outputs to display correctly in a listbox working with a WPF Powershell project. I have an example where in powershell it displays fine like below.

PS output

However my listbox it will show as below

Listbox Output

I want it to just show the SamAccountName so PS.Test in this case. Used the below line but to no avail Not entirely sure how to do this tried a few things

$ListBoxLeft.DisplayMember = "SamAccountName";

The command i was using is

(Get-ADUser -Filter "Name -like '*$query*'") | Select SamAccountName | Sort -Property SamAccountName

there is a textbox where the name is pulled from. All new to me this side of it so trying to play around and learn so i can utilise the functions in various scripts in the future.

Code for the task which populates the listbox

function SearchDGUserClick
{
    param($sender, $e)

 $query = $DGUserSearchText.Text
 $UserSearch = (Get-ADUser -Filter "Name -like '*$query*'") | Select SamAccountName | Sort -Property SamAccountName

  foreach ($item in $UserSearch) {
    $DGMemberSearchListBox.Items.Add($item)
    
  }


}

Solution

  • Just add the value of the SamAccountName property to the Items collection:

    foreach ($item in $UserSearch) {
      $DGMemberSearchListBox.Items.Add($item.SamAccountName)
    }