Home > Back-end >  Where-Object not filtering
Where-Object not filtering

Time:11-30

Why isn't where-object working in this case?

$controlFlowArgs = @{ waitForEnter = $false }
$controlFlowArgs | Format-Table
$controlFlowArgs | Format-List
$result = $controlFlowArgs | Where-Object -FilterScript { $_.Name -eq "waitForEnter" }
$result

Output

Name         Value # Format-Table
----         -----
waitForEnter False

Name  : waitForEnter # Format-List
Value : False

# Missing result would be here

CodePudding user response:

$controlFlowArgs is a HashTable. You should probably think it differently.

$result = $controlFlowArgs | Where-Object { $_["waitForEnter"] }

would store $false in $result. Else you can use the Hashtable directly:

if ($controlFlowArgs["waitForEnter"]) {
  ...
}

CodePudding user response:

Where-object is working fine. In this example, only the 'joe' hashtable appears. Confusingly the format takes up two lines.

@{name='joe';address='here'},@{name='john';address='there'} | ? name -eq joe

Name                           Value
----                           -----
name                           joe
address                        here

It's still considered one thing:

@{name='joe';address='here'},@{name='john';address='there'} | ? name -eq joe | 
  measure-object | % count

1

If you want the value itself, use foreach-object (or select-object -expandproperty):

@{name='joe';address='here'},@{name='john';address='there'} | ? name -eq joe | 
  % name

joe

Usually powershell works with pscustomobjects:

[pscustomobject]@{name='joe';address='here'},
  [pscustomobject]@{name='john';address='there'} | ? name -eq joe

name address
---- -------
joe  here
  • Related