Forum Discussion

williamdominski1445's avatar
williamdominski1445
Copper Contributor
Jul 05, 2023
Solved

Windows 10 Powershell conditional is only reading the first digit in number

Hello, I am trying to use a powershell script to parse through a json file and select entries that have a cyclomatic complexity > 15. There are a couple of entries ranging from 12-18 in terms of val...
  • LainRobertson's avatar
    Jul 06, 2023

    williamdominski1445 

     

    Hi, William.

     

    This is because - in PowerShell - the operand on the right-hand side of the operator is cast to the type of the operand on the left-hand side before the comparison is made.

     

    So, where you thing you are comparing (based on your code on line 4):

     

    [int] $_.value to [int] 18

     

    You're actually comparing:

     

    [string] $_.value to [string] "18"

     

    This is because the JSON type for "value" (from the file data) is going to be string.

     

    The easiest (but not failsafe) way to deal with this is to switch the operands around so that the integer operand sits to the left of the operator (which therefore also needs changing):

     

    $selectedEntries = $jsonContent | Where-Object {(18 -lt $_.value)}

     

    Here's a little demonstration of the automatic type conversion - which you can easily test with yourself.

     

     

    Cheers,

    Lain

Resources