有办法在数组中选择非空/空元素吗?例如:
当前csv:( "___“表示空,如'')
Col1 Col2
1 "hello"
2 "adsf"
3 "hi"
__
__我想要的结果:
$array = (1,2,3)发布于 2020-10-13 19:56:35
假设您有足够的内存将CSV文件完整地读取到内存中,则可以将成员访问枚举与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 ''注意:
@(),数组子表达式运算符,用于确保$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]确保从管道收集的输出始终被视为数组,即使只返回一个值(另一种选择是将整个管道包装在@(...)中)。发布于 2020-10-13 19:24:33
假设Col1是一个字符串
Import-Csv C:\path\to\test.csv | ?{![string]::IsNullOrEmpty($_.Col1)}https://stackoverflow.com/questions/64341708
复制相似问题