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

Copper Contributor


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 value, however as soon as I set the conditional to be anything greater than 9 (ie, 10), all entries above one show. If I tried doing a value greater than 88, all values above 8 would show. Any help would be greatly appreciated.



1 Reply
best response confirmed by williamdominski1445 (Copper Contributor)



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.