简体   繁体   中英

Where-Object not filtering

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

$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"]) {
  ...
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM