In PowerShell 7.4.5, I ran into a weird issue with Where-Object
a.k.a. ?
.
Let’s assume $players
is System.Collections.Generic.List
and contains for example these objects that I get from Invoke-RestMethod
:
Id : 536069
User_id : 2739325
Elo1v1 : 1511
Elo2v2Solo : 1907
Elo2v2Team : 2222
TeamIndex : 0
PlayerIndex : 2
Id : 278305
User_id : 1735386
Elo1v1 : 1443
Elo2v2Solo : 1788
Elo2v2Team : 1279
TeamIndex : 1
PlayerIndex : 1
and $myUserId
is 1735386
.
I then tried to run:
$myself = $players | ? User_id -eq $myUserId | Select -First 1
but it caused a lot of chaos and debugging as it worked under some scenarios when my further code was different, then consistently stopped working completely – $myself
was empty.
After bunch of tries, I changed it to:
$myself = $players | ? { $_.User_id -eq $myUserId } | Select -First 1
and it started working consistently.
Why? What’s wrong with the first version? I would assume something related to the underscore in the property name, but then this works fine and always returns an object:
$opponent = $players | ? User_id -ne $myUserId | Select -First 1
I couldn’t find anything about underscore or similar characters in docs.
10