在类似表的自定义对象中检索值

时间:2017-02-21 15:27:24

标签: arrays powershell

我试图从表中检索一个值(从csv文件导入)。我可以用2行来做,但我想我错过了一些东西,它可能只在一行中完成。

以下是代码:

$bar = $foo | where-Object  {$_.Myvalue -eq "network"  }
$bar.label

这实际上是有效的。但我想我可以在一行内完成,但我发现了。

4 个答案:

答案 0 :(得分:4)

尝试Select-Object -ExpandProperty

$foo | where-Object {$_.Myvalue -eq "network" } | Select-Object -ExpandProperty Label

Foreach-Object

$foo | where-Object {$_.Myvalue -eq "network" } | Foreach-Object { $_.Label }

答案 1 :(得分:2)

您可以使用Select-Object cmdlet检索值:

$foo | where-Object {$_.Myvalue -eq "network" } | Select-Object -expand label

答案 2 :(得分:1)

如果您不想保留结构,

($foo | Where-Object -FilterScript { $_.MyValue -eq "network" }).label应该有用。

答案 3 :(得分:0)

解决方案示例。有些已被提议。

$foo=import-csv "C:\temp\gogo.csv"

#possibility 0, with ultra short version of where and select
$foo | ? Myvalue -eq "network" | Select label

#possibility 1, with short version of where and select
$foo | Where Myvalue -eq "network" | Select label

#possibility 2, with property on list result
($foo | Where Myvalue -eq "network").label

#possibility 3, with where property
$foo.Where({$_.Myvalue -eq "network"}).label

#possibility 4, with if into foreach
$foo | %{ if ($_.Myvalue -eq "network") {$_.label}}

#possibility 5, with format table
$foo | Where Myvalue -eq "network" | Format-Table label