0

For the CSV file below, I want to search for each type of Fruit in the file and display the last entry via PowerShell. I've tried the following but I'm getting a blank output.

$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 file:

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

Expected output:

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

Can anyone help in resolving this?

1 Answer 1

3

Your expected output is probably wrong since last Orange count is 13.

Anyhow, You can use the Group-Object cmdlet to group your result based on the Fruit property and select the last entry using the -1 index:

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

Output:

Fruit  Weight   
-----  ------   
Apple  2 pounds 
Orange 13 pounds
Kiwi   3 pounds 
Grape  3 pounds 
Sign up to request clarification or add additional context in comments.

1 Comment

You are welcome. You main issue with your code is that you are using $fruit in your Select-String cmdlet instead of $fruit.Fruit because this way you retrieve the current fruit

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.