Hi Gents,
Practicing on comparison parameters.
I have a csv file that consists below contents.
<colgroup><col style=“width: 48pt;” span=“3” width=“64” /> </colgroup>
col1 |
col2 |
col3 |
21 |
22 |
23 |
31 |
32 |
33 |
41 |
42 |
43 |
a |
b |
c |
A |
B |
C |
AA |
bb |
CC |
aa |
BB |
cc |
Aa |
Bb |
cC |
Import-Csv C:\Users\Sugandhan\Desktop\Test.csv | Where-Object {$_.col1 -lt '3333'}
If i run the above command it gives only below output
col1 col2 col3
21 22 23
31 32 33
Not the third Row (41). May i know the reason behind this?
The same way -gt behaves.
PS C:> Import-Csv C:\Users\Sugandhan\Desktop\Test.csv | Where-Object {$_.col1 -gt ‘3333’}
col1 col2 col3
41 42 43
a b c
A B C
AA bb CC
aa BB cc
Aa Bb cC
I believe this would be because your imported data is a string and not an integer. Strings sort differently, you can see this in the below test:
PowerShell sees these numbers as integers and operates as you are expecting:
41 -lt 3333
True
Now if we cast your first number as a string:
[string]41 -lt 3333
False
You could try casting your item as an integer, not able to test this so may need refined:
Test.csv | Where-Object {[int]$_.col1 -lt '3333'}
Only one change would need to happen to this, because the original set of data are strings, errors will occur trying to convert letters (a, aa, AA, etc.) to a type Int32:
Test.csv | Where-Object {[int]$_.col1 -lt '3333'}
However, doing a Where-Object to do a regex match for Integers before casting should work:
Test.csv | Where-Object{ $_.col1 -match '\d+'} | Where-Object {[int]$_.col1 -lt 3333}
Instead of comparing strings, you can compare numbers:
$Data = Import-Csv .\csv2.csv
$Data | Where-Object {$_.col1 -as [Int]} # Integers Only
$Data | Where-Object {-not ($_.col1 -as [Int])} # Non-Integers Only
$Data | Where-Object {($_.col1 -as [Int]) -and ($_.col1 -as [Int])-lt 3333} # Integers Less Than 3333
$Data | Where-Object {($_.col1 -as [Int]) -and ($_.col1 -as [Int])-gt 3333} # Integers More Than 3333
'33' -gt 3333 # False ==> comparing strings
'34' -gt 3333 # True ==> comparing strings
33 -gt 3333 # False ==> comparing Integers
34 -gt 3333 # False ==> comparing Integers
'33' -gt '3333' # False ==> comparing strings
'34' -gt '3333' # True ==> comparing strings
33 -gt '3333' # False ==> comparing Integers
34 -gt '3333' # False ==> comparing Integers
Thanks All.
Can anyone suggest any blog/document to learn about “when and where to use [int],[string],etc…?”