Reputation: 271
I have a drop down list that's being populated by a CSV file. There are many columns in the CSV, but it only pulls from the Name
column. Here's what I have that works just fine in most Win 7, and all Win 8+ PC's I've tried it on.
$customers = Import-CSV "$dir\Apps\customers.csv"
$List = $customers.name | Sort-Object
After that there's a ForEach
loop to put each item from the list into the menu.
Lately I've been noticing an issue on a couple Win 7 PC's that I can't figure out. The import option doesn't work unless I specify all the headers with the -Header
option. I get this error:
After getting it to import correctly by adding all the headers I can't get it to save $customers.name
into the $List
variable, with or without the sorting. However, if I provide an index number (ex $customers[2].name
) it works.
To work around this I've looked at ways to measure the number of rows in the CSV by using the following options after $customers
:
$csvlength = Get-Content "$dir\Apps\customers.csv" | Measure-Object - lines
or
$csvlength = Import-CSV "$dir\Apps\customers.csv" | Measure-Object
From there I can see the length by looking at $csvlength.lines
or $csvlength.count
.
Is there a way to use that information to save the list of names into $List
? I've tried something like this with no success:
$List = $customers[0-$csvlength.count] | Sort-Object
Also, I've noticed that when importing the headers it includes Name
in the list. If at all possible I'd like to not include the header. I also have a line at the end of the CSV that has other info in it, but no name. That shows up as a blank line. If possible I'd like that to be removed as well.
Upvotes: 1
Views: 1267
Reputation: 200293
PowerShell v2 $array.Foo
only allows access to a property Foo
of the array object itself, not to a property Foo
of the array elements. Allowing access to element properties via the array variable is one of the major changes that was introduced with PowerShell v3.
To work around this limitiation in v2 you need to expand the property before sorting:
$List = $customers | Select-Object -Expand name | Sort-Object
Upvotes: 2