2017-02-21 63 views
1

我試圖從表格中檢索值(從csv文件導入)。我可以用2行來完成,但我想我錯過了一些東西,它可能只在一行中完成。檢索表格式自定義對象中的值

下面是代碼:

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

這實際上是工作。但我想我可以在一條線內做到這一點,但我發現如何。

+1

PS3 +:'$ foo | ? Myvalue -eq「network」| select -expand label' – wOxxOm

+1

或'($ foo | Where-Object {$ _。Myvalue -eq「network」})。標籤' –

回答

2

可以使用Select-Object cmdlet來檢索值:

$foo | where-Object {$_.Myvalue -eq "network" } | Select-Object -expand label 
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

這正是他需要它的原因。 '$ foo'是一個具有標籤屬性的對象,他希望從中獲得該值。沒有展開,他會收到一個只有該屬性的新對象。隨着擴大他將得到「標籤」的實際價值 –

+0

好吧我的藉口:) +1 4 U – Esperento57

1

($foo | Where-Object -FilterScript { $_.MyValue -eq "network" }).label應該工作,如果你不希望保留結構。

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