当我尝试过滤数据时,我有一组对象没有按预期返回数据。
数据:
Date Batch
---- -----
04/08/2008 1
04/08/2008 2
04/08/2008 3
04/08/2008 10
04/08/2008 11
我的代码:
$table = @{}
$table = import-csv e:\report.csv
Foreach($item in $table.GetEnumerator())
{
If (($item.date -eq '4/8/2008') -and ($item.batch -le 100) )
{
$item
}
}
我希望它返回所有项目,但我只得到:
Date Batch
---- -----
04/08/2008 1
04/08/2008 10
我错过了什么?
答案 0 :(得分:2)
我错过了什么?
字符串不是数字的事实:-)
Import-Csv
将所有列值视为字符串,因此您将字符串 "3"
与 100
进行比较,而不是数字 > 3
- 按字母顺序,100
在 3
之前(第一个字符 "1"
与第一个字符 "3"
)。
将 $item.batch
转换为数字类型:
foreach($item in Import-Csv E:\report.csv)
{
If (($item.date -eq '4/8/2008') -and ([int]$item.batch -le 100) )
{ # Look, here
$item
}
}
... 或者,翻转操作数,使数字参考值 (100
) 成为左侧参数:
If (($item.date -eq '4/8/2008') -and (100 -gt $item.batch) )
这将导致 PowerShell 在比较之前将 $item.batch
转换为数字类型