有没有一种方法可以将非空/空元素选择到数组中?例如:
当前的csv :(“___”代表空,例如“”)
Col1 Col2
1 "hello"
2 "adsf"
3 "hi"
__
__
结果我想要:$array = (1,2,3)
最佳答案
假设您有足够的内存来将CSV文件完全读入内存,则可以将member enumeration与PowerShell的比较运算符的数组过滤功能(在这种情况下为-ne
)结合使用:
# Simulate reading a CSV file into an array of $objects.
# (instead of: $objects = Import-Csv ...)
$objects =
@'
Col1,Col2
1,"hello"
2,"adsf"
3,"hi"
,"..."
,"..."
'@ | ConvertFrom-Csv
# .Col1 returns the "Col1" column values as an array,
# and -ne '' filters out the empty-string values.
$array = @($objects.Col1) -ne ''
注意:@()
(即array-subexpression operator)用于确保$objects.Col1
返回值的数组,即使CSV文件恰好只有一个数据行。-ne
充当过滤器(而不是返回$true
或$false
),并返回匹配元素(不是空字符串的元素)的子数组。请注意,即使使用单元素LHS,结果也是数组。否则,如果CSV文件太大而无法完全读入内存,则需要使用管道(这会比较慢):
[array] $array =
@'
Col1,Col2
1,"hello"
2,"adsf"
3,"hi"
,"..."
,"..."
'@ | ConvertFrom-Csv | ForEach-Object { if ('' -ne $_.Col1) { $_.Col1 } }
注意:[array]
确保从管道收集的输出始终被视为一个数组,即使仅返回一个值(替代方法是将整个管道包装在@(...)
中)。 关于powershell - 如何选择非空CSV单元格并将其放入Powershell中的数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64341708/