0

I have an array of objects that is not returning data as expected when I try to filter it.

Data:

Date           Batch
----           -----
04/08/2008     1
04/08/2008     2
04/08/2008     3
04/08/2008     10
04/08/2008     11

My code:

$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
    }
}

I would expect it to return all items but I only get:

Date           Batch
----           -----
04/08/2008     1
04/08/2008     10

What am I missing?

1
  • 2
    When you read from a CSV, all values are strings. If you want to do a numerical comparison, you need numeric types. You can simply cast --> [int]$item.batch -le 100. The alternative is let the left-hand side be the data type you want --> 100 -ge $item.batch Commented Jan 14, 2021 at 14:13

1 Answer 1

2

What am I missing?

The fact that strings are not numbers :-)

Import-Csv treats all column values as strings, so you're comparing the string "3" to 100, not the number 3 - and alphabetically, 100 precedes 3 (first character "1" vs first character "3").

Cast $item.batch to a numerical type:

foreach($item in Import-Csv E:\report.csv)
{
    If (($item.date -eq '4/8/2008') -and ([int]$item.batch -le 100) )
    {                                      # Look, here
        $item
    }
}

... or, flip the operands around, so that the numerical reference value (100) is the left-hand side argument:

If (($item.date -eq '4/8/2008') -and (100 -gt $item.batch) )

This will cause PowerShell to convert $item.batch to a numerical type before comparing

Sign up to request clarification or add additional context in comments.

1 Comment

I knew it was a simple thing I was overlooking! Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.