powershell 数组返回意外结果

时间:2021-01-14 14:04:01

标签: powershell

当我尝试过滤数据时,我有一组对象没有按预期返回数据。

数据:

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

我错过了什么?

1 个答案:

答案 0 :(得分:2)

<块引用>

我错过了什么?

字符串不是数字的事实:-)

Import-Csv 将所有列值视为字符串,因此您将字符串 "3"100 进行比较,而不是数字 > 3 - 按字母顺序,1003 之前(第一个字符 "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 转换为数字类型