Comparing strings and integers

Saw an interesting problem involving the comparison of 2 numbers. In reality its was comparing strings and integers.

The starting point was a CSV file but as I showed last time you can create a CSV in memory

PS> $file = @'
>> "Count";"Value"
>> "3";"Year1"
>> "1";"Year1"
>> "5";"Year3"
>> "8";"Year4"
>> "10";"Year15"
>> "12";"Year6"
>> "88";"Year7"
>> "154";"Year2"
>> '@ | ConvertFrom-Csv -Delimiter ';'

PS> $file

Count Value
----- -----
3     Year1
1     Year1
5     Year3
8     Year4
10    Year15
12    Year6
88    Year7
154   Year2

The goal is to get all lines where Count is greater than or equal to 8.

The obvious starting point is

PS> $file | where Count -ge 8
Count Value
----- -----
8     Year4
88    Year7

Which doesn’t supply the right answer.

Checking the object created from the CSV file

PS> $file | Get-Member

    TypeName: System.Management.Automation.PSCustomObject

Name        MemberType   Definition
----        ----------   ----------
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()
GetType     Method       type GetType()
ToString    Method       string ToString()
Count       NoteProperty string Count=3
Value       NoteProperty string Value=Year1

Count is a string

With comparison operators the RIGHT hand side is converted to be the same as the LEFT hand side if the types don’t match. So in effect you’re getting

PS> "154" -ge "8"
False

You need to force the LEFT hand side to be an integer

PS> [int]"154" -ge "8"
True

PS> ("154" -as [int]) -ge "8"
True

That makes the code to work with the CSV

PS> $file | where {[int]$_.Count -ge 8}

Count Value
----- -----
8     Year4
10    Year15
12    Year6
88    Year7
154   Year2

or

PS> $file | where {($_.Count -as [int]) -ge 8}

Count Value
----- -----
8     Year4
10    Year15
12    Year6
88    Year7
154   Year2

CSV files are great but you have to remember about type conversion when you’re comparing properties

Advertisements
This entry was posted in Powershell. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s