[英]How to import CSV column? Import-Csv not working as planned
I have a drop down list that's being populated by a CSV file. 我有一个由CSV文件填充的下拉列表。 There are many columns in the CSV, but it only pulls from the
Name
column. CSV中有很多列,但仅从“
Name
列中提取。 Here's what I have that works just fine in most Win 7, and all Win 8+ PC's I've tried it on. 这就是我在大多数Win 7和我尝试过的所有Win 8+ PC上都能正常使用的功能。
$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. 之后,有一个
ForEach
循环将列表中的每个项目放入菜单。
Lately I've been noticing an issue on a couple Win 7 PC's that I can't figure out. 最近,我一直注意到几台Win 7 PC无法解决的问题。 The import option doesn't work unless I specify all the headers with the
-Header
option. 除非我使用
-Header
选项指定所有标题,否则导入选项将-Header
。 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. 通过添加所有标头使其正确导入后,无论是否进行排序,我都无法将
$customers.name
保存到$List
变量中。 However, if I provide an index number (ex $customers[2].name
) it works. 但是,如果我提供一个索引号(例如
$customers[2].name
),它将起作用。
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
: 为解决此问题,我研究了通过在
$customers
之后使用以下选项来测量CSV中的行数的方法:
$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
. 从那里,我可以通过查看
$csvlength.lines
或$csvlength.count
看到长度。
Is there a way to use that information to save the list of names into $List
? 有没有一种方法可以使用该信息将名称列表保存到
$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. 另外,我注意到导入标题时,它在列表中包括
Name
。 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.
CSV的末尾还有一行,其中包含其他信息,但没有名称。 That shows up as a blank line.
这显示为空白行。 If possible I'd like that to be removed as well.
如果可能的话,我也希望将其删除。
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 . PowerShell的V2
$array.Foo
只允许访问一个属性Foo
数组对象本身,而不是一个性质Foo
数组元素 。 Allowing access to element properties via the array variable is one of the major changes that was introduced with PowerShell v3. 允许通过数组变量访问元素属性是PowerShell v3引入的主要更改之一。
To work around this limitiation in v2 you need to expand the property before sorting: 要解决v2中的这种局限性,您需要在排序之前扩展属性:
$List = $customers | Select-Object -Expand name | Sort-Object
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.