Home > Enterprise >  Import csv file and return the quantity of a specific fruit from a specific owner on powershell
Import csv file and return the quantity of a specific fruit from a specific owner on powershell

Time:09-27

I need to create a script that passes me the type of fruit and the owner as a parameter and returns the quantity of said fruit from this csv:

amount;fruit;owner
3;orange;antonio
2;orange;harry
4;pear;rebeca
1;apple;sonia
12;pear;juan
2;orange;antonio

should execute the script like this:

ps> fruit.ps1 -fruit orange -owner antonio

The result should be 5

My code is:

New-Item fruit.csv -Force
Add-Content fruit.csv 'amount;fruit;owner'
Add-Content fruit.csv '3;orange;antonio'
Add-Content fruit.csv '2;orange;harry'
Add-Content fruit.csv '4;pear;rebeca'
Add-Content fruit.csv '1;apple;sonia'
Add-Content fruit.csv '12;pear;juan'
Add-Content fruit.csv '2;orange;antonio'

$ficherofruta = Import-Csv fruit.csv -Delimiter ";"
[string] $acumulatorfruit
[string] $acumulatorowner
$amount = 0
if($amountfruta.fruit -eq "orange")
 {
if($amountfruit.owner-eq antonio)
$cantidad
}
}
Foreach($amountfruta in $fruit) 
{

Switch ($amountfruta.fruit)
{
 "orange" { $acumalator = [string]$fruitamount.fruit }
 "apple" { $acumulator = [string]$fruitamount.fruit }
 "pear" { $acumulator = [string]$fruitamount.fruit }
 }
Switch ($amountfruta.owner){
"antonio" { $acumuladtorowner = [string]$fruiatmount.owner}
 "pepito" { $acumuladtorowner = [string]$fruiatmount.owner}
 "rebeca" { $acumuladtorowner = [string]$fruiatmount.owner}
 "sonia" { $acumuladtorowner = [string]$fruiatmount.owner}
 "juan" { $acumuladtorowner = [string]$fruiatmount.owner }
}
Write-Host $acumulator
}

I want to join the Switch "fruit" with "owner" switch and group by the exit with amount

CodePudding user response:

I suggest solving your problem with the help of the Group-Object cmdlet:

# Create a a sample CSV file.
$null = New-Item fruit.csv -Force -Value @'
amount;fruit;owner
3;orange;antonio
2;orange;harry
4;pear;rebeca
1;apple;sonia
12;pear;juan
2;orange;antonio
'@

# Implement the code as a function, in this example.
function fruit {

  param(
    [Parameter(Mandatory)] $fruit,
    [Parameter(Mandatory)] $owner
  )

  Import-Csv -Delimiter ';' fruit.csv | 
    Group-Object fruit, owner | 
    Where-Object { $_.Values[0] -eq $fruit -and $_.Values[1] -eq $owner } |
    ForEach-Object { ($_.Group | Measure-Object -Sum amount).Sum }

}

# Sample call
# -> 5
fruit -fruit orange -owner antonio
  • Related