Items in listbox
Forum rules
Do not post any licensing information in this forum.
Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
Do not post any licensing information in this forum.
Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
Items in listbox
Hi is they any way to take the items that are listed in a listbox and export them to a text file or csv? Thanks for any help in advance.
- Alexander Riedel
- Posts: 8479
- Last visit: Thu Mar 28, 2024 9:29 am
- Been upvoted: 37 times
Re: Items in listbox
Sure there is. Create a stringbuilder object, iterate over the items in the list and add them line by line.
The use something like out-file to write the string to a file.
If you use a listview rather than a listbox, then you can use the Items property. It has a CopyTo method that can be used to export the items to an array, which in turn you can pipe to out-file.
(Not sure at the moment if you can pipe the Items property itself)
Depending on the amount of data, the method of writing to a file may be of interest.
See https://blogs.technet.microsoft.com/gbo ... to-a-file/
The use something like out-file to write the string to a file.
If you use a listview rather than a listbox, then you can use the Items property. It has a CopyTo method that can be used to export the items to an array, which in turn you can pipe to out-file.
(Not sure at the moment if you can pipe the Items property itself)
Depending on the amount of data, the method of writing to a file may be of interest.
See https://blogs.technet.microsoft.com/gbo ... to-a-file/
Alexander Riedel
SAPIEN Technologies, Inc.
SAPIEN Technologies, Inc.
Re: Items in listbox
Here is a simple way to test and inspect and forms control without a form.
At a CLI prompt do the following (PS5)
At a CLI prompt do the following (PS5)
- PS > add-type -AssemblyName System.windows.forms
- PS > using namespace System.Windows.Forms
- PS > $lb = [Listbox]::New()
- PS > $lb.Items.AddRange(@('one','two','three'))
- PS > $lb.Items
- one
- two
- three
- PS > $lb.Items | Out-File lbtest.txt
- PS > cat lbtest.txt
- one
- two
- three
- # to a csv
- PS >$lb.Items | Export-Csv lbtest.csv -Header LBItems -NoType
- PS >
Re: Items in listbox
Here is how to use objects in a listbox and export them as a CSV. You can use PowerShell to export the same as any other object collection.
If you need to export only selected items then use $lb.SelectedItems instead of $lb.DataSource.
- add-type -AssemblyName System.windows.forms
- using namespace System.Windows.Forms
- $lb = [Listbox]::New()
- $files = Get-ChildItem c:\
- # convert to loadable collection
- $lb.DataMember = 'Name' # pick property to display
- $lb.DataSource = [collections.arraylist]$files
- $lb.DataSource | Export-Csv lbtest.csv -NoType
- $lb.DataSource | Export-CliXml lbtest.clixml
- $lb.DataSource | Format-Table