Home > Mobile >  Check if value falls within a specific range powershell
Check if value falls within a specific range powershell

Time:05-21

I am having a code which is giving me 2 values like below

            $pattern = '\s(-?\d .?\d )\s'
            $RX_Val = [regex]::Matches($RXTX_Data[0], $pattern).Value
            $TX_Val = [regex]::Matches($RXTX_Data[1], $pattern).Value
PS C:\Windows\system32> $RX_Val
 -3.4 

PS C:\Windows\system32> $TX_Val
 -2.3 

Need get RX and TX value should fall under range -1 to -7 like the above 2 values falls within the range

if the values are like 1 and -8 respecively, then it should give error

I tried below code, but not getting the proper response


            if((($RX_Val -gt -1) -and ($RX_Val -lt -7)))# -and (($TX_Val -gt '-1') -and ($TX_Val -lt '-7')))
            {
                Write-Host "OK"
            }
            else
            {
                Write-Host "NOT OK"
            }

also tried

$RX_Val -In -1..-7

please let me know what i am missing here

Tried given solution in below way

            $RX_Val = [int][regex]::Matches($RXTX_Data[0], $pattern).Value
            $TX_Val = [int][regex]::Matches($RXTX_Data[1], $pattern).Value

           if(($RX_Val -in -1..-7) -and ($TX_Val -in -1..-7))
            {
                Write-Host "OK"
            }
            else
            {
                $RXTX_Data | Out-File -FilePath "E:\$file_name" -Force
            }

but failed for below scenario as the values are converted to int. it is suppose to print OK

$RX_Val=-0.1 

$TX_Val=-1.5 

CodePudding user response:

The issue is that the value return by your regex extraction is a STRING. You need to convert it to an INT to be able to do your calculation.

$RX_Val = [int][regex]::Matches($RX, $pattern).Value
$TX_Val = [int][regex]::Matches($TX, $pattern).Value

Sure you can make the logic work from there. As a bonus, the cast to [int] will also take care of the whitespace left from the regex.

  • Related