2017-10-16 52 views
0

对于下面的CSV文件,我想在文件中搜索每种类型的Fruit并通过PowerShell显示最后一个条目。我试过以下,但我得到一个空白输出。PowerShell foreach选择字符串查询

$fruits = Import-Csv Fruits.csv | select Fruit | sort-object -Property Fruit -Unique 

foreach ($fruit in $fruits) 
{ 
Import-CSV Fruits.csv | Select-String -Pattern $fruit 
} 

Fruits.csv文件:

Fruit, Weight 
Apple, 3 pounds 
Apple, 4 pounds 
Apple, 10 pounds 
Orange, 3 pounds 
Kiwi, 3 pounds 
Grape, 2 pounds 
Orange, 13 pounds 
Grape, 3 pounds 
Apple, 6 pounds 
Apple, 2 pounds 

预期输出:

Apple, 2 pounds 
Orange, 3 pounds 
Kiwi, 3 pounds 
Grape, 2 pounds 

任何人都可以在解决这个帮助吗?

回答

3

您的预期输出可能是错误自上次橙色计数是。

总之,您可以使用Group-Object cmdlet来组你的结果基础上,Fruit财产和使用-1指数选择的最后一个条目:

Import-Csv Fruits.csv | 
    Group Fruit | 
    ForEach-Object { 
     $_.Group[-1] 
    } 

输出:

Fruit Weight 
----- ------ 
Apple 2 pounds 
Orange 13 pounds 
Kiwi 3 pounds 
Grape 3 pounds 
+0

感谢那些诀窍! – PowershellNewbie

+0

不客气。你的代码的主要问题是你在'Select-String' cmdlet中使用'$ fruit'而不是'$ fruit.Fruit',因为这样你可以检索当前的水果 –