Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PowerShell foreach选择字符串查询_Powershell - Fatal编程技术网

PowerShell foreach选择字符串查询

PowerShell foreach选择字符串查询,powershell,Powershell,对于下面的CSV文件,我想搜索文件中的每种水果类型,并通过PowerShell显示最后一个条目。我尝试了以下方法,但得到的是空白输出 $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.cs

对于下面的CSV文件,我想搜索文件中的每种水果类型,并通过PowerShell显示最后一个条目。我尝试了以下方法,但得到的是空白输出

$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

有人能帮忙解决这个问题吗?

您的预期输出可能是错误的,因为上次的橙色计数是13

无论如何,您可以使用
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 

您的预期输出可能是错误的,因为最后一个橙色计数是13

无论如何,您可以使用
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 

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