Home > Net >  Operator -gt and -le / Problem with negative numbers
Operator -gt and -le / Problem with negative numbers

Time:07-22

i have the following code snippet where i change the values in a column (named G) of a csv to Y if the integer value is greater then 1 and to N if it is equal to 1 and smaller.

ForEach-Object {if ($_.G -gt '1') {$_.G = 'Y'} if ($_.G -le '1') {$_.G = 'N'} $_} 

It works fine with the exception of negative numbers. I always get a Y. I don't have any idea. Example data:

F,G item1, -58 item2, -77 item3, 562

Does anyone have an idea?

Regards, Hubertus

CodePudding user response:

In order to evaluate the $_.G property as a number you need to specify the type as [int]. Example using your code:

    $testObject = New-Object PSObject -Property @{
        G='-1'
    }
    
    $testObject| %{ 
    if ([int]$_.G -gt 1) 
    {
        $out = "{0} is greater than 1" -f $_.G
        Write-Host $out -ForegroundColor Green  
        [string]$_.G = "Y"              
    } 
    elseif ([int]$_.G -le 1) 
    {
        $out = "{0} is Less than 1" -f $_.G
        Write-Host $out -ForegroundColor Green   
        [string]$_.G = "N" 
    }    
}

Note: In order to assign $_.G as a string you have to change the type to [string]. In my opinion, I would use another property to indicate "Y/N" instead of flipping the type back and forth on the property.

CodePudding user response:

The left side of -le or -gt controls the type for both sides, int32 (integer) in this case. You probably want an else in there, to not look at the G again after changing it.

'G
-1
1
2' | 
convertfrom-csv | 
ForEach-Object {
  if (1 -le $_.G) 
    {$_.G = 'Y'} 
  else
    {$_.G = 'N'} 
  $_
} 

G
-
N
Y
Y
  • Related