2

I like to know which method should I overload to the object get a custom text string display in PowerShell Windows.Forms.ListBox. I have tried this and other variations but to no avail:

$vms_listbox = New-Object System.Windows.Forms.ListBox

$vms = Get-VM
#
# Overload ToSTring (I thought this would do)
#
$vms | Add-Member ScriptMethod ToString { $This.Name } -Force
$vms | Foreach {
    [Void]$vms_listbox.Items.Add($_)
}

I have tried ith Add-Member ScriptProperty, CodeMethod, CodeProperty, but the listbox still not show the value I intend to show which in this case, the Virtual machine name.

I could have add to the list with the virtual name as: Items.Add($_.Name), but I prefer to add the instance to the list so I can retrieve it later.

Thanks in advance.

1 Answer 1

3

You need to tell he listbox which property contains the display-friendly name for the items.

Replace:

$vms_listbox = New-Object System.Windows.Forms.ListBox

with:

$vms_listbox = New-Object System.Windows.Forms.ListBox
$vms_listbox.DisplayMember = "Name"
Sign up to request clarification or add additional context in comments.

1 Comment

This sure does exactly what I wanted. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.