Home > database >  PowerShell: select lines from object collection where property -lt X
PowerShell: select lines from object collection where property -lt X

Time:10-29

so I have this table in variable $res

hostname OSshort freeGBonC


server1 w2k12 29,23
server2 w2k12 32,10
server3 w2k12 19,26

I can't seem to understand how to select lines with freeGBonC lower then some value. If I try

$res|where {$_.freeGBonC -lt 6}

it shows all lines! If I do -gt 6 it shows nothing! What kind of logic is this?

CodePudding user response:

I would assume the values on the property freeGBonC are of the type string hence why the comparison is showing unexpected results.

Try using this, I think it should work:

$csv = @'
"hostname","OSshort","freeGBonC"
"server1","w2k12","29,23"
"server2","w2k12","32,10"
"server3","w2k12","19,26"
'@ | ConvertFrom-Csv

$csv | Where-Object {[double]$_.freeGBonC.Replace(',','.') -lt 29}

Results:

hostname OSshort freeGBonC
-------- ------- ---------
server3  w2k12   19,26 

I guess PowerShell is smart enough to compare the string with a double as long as the double has the correct sign (.) so casting [double] or [decimal] is not even needed. Note that, , is for arrays.

PS \> $csv.freeGBonC.ForEach({$_.Replace(',','.') -lt 29})
False
False
True

Thanks @mklement0 for pointing this out, it is in fact needed to cast [double] if the string is on the left hand side of the operator else we will get unwanted results:

'10.0' -lt 2 # => True
2 -gt '10.0' # => False
[double]'10.0' -lt 2 # => False
  • Related