Mr Deans Mr Deans - 2 months ago 14x
PowerShell Question

Powershell Math CSV

Very little out there about this subject so over to the experts.

Say I import a csv into powershell with three columns A, B and Result

I wish to divide one column by another and add their result to the result column.

On testing this it is simply coming out with a single column stating Length 21 rather than the result.

The code I am using is simulated as below.

$csv = Import-Csv c:\test.csv
$csvout = Export-Csv C:\testb.csv

$csv | ForEach-Object {
$_.result = [math]::round($_.A / $_.B, 0)

export-csv $csvout -NoTypeInformation

In my head this seems correct but there is something that I obviously cannot see.

Anyone more familiar with using powershell math functions with CSV than I am?

Let me know if you require further information...

Kind Regards



You're missing a pipe between the end of ForEach-Object and Export-Csv and you forgot to put anything in the output pipeline.

Finally, Export-Csv returns nothing so your use of Export-Csv here is a bit odd.

$csv = Import-Csv c:\test.csv
$csvout = "C:\testb.csv"

$csv | ForEach-Object {
    # Do the math
    $_.result = [math]::round($_.A / $_.B, 0)
    # Output the object (which contains A, B and result)
} | Export-Csv $csvout -NoTypeInformation