1

i have a csv sheet like one given below, (some cells can be empty, actual sheet i have is having upto disk 20),

ID   name disk1 disk2 disk3
001  abc  50    50    50 
002  def  100   100     
003  xyz  50

I need to input this sheet to powershell script and add all three "disk" fields alone for each record and print it out, something like given below, only sum is sufficient not required ID or name fields, preferably i need a function to call for each record to return back the sum

150
200
50

tried this so far but no luck

$coll = import-csv "C:\input.csv"
foreach ($record in $coll)
{
    for ($i=1; $i -lt 4; $i++)
    {
        [int]$totaldisk = @()
        $diskname = "disk"+$i
        $totaldisk += $record.$diskname
    }
    $totaldisk
 }
3
  • What have you tried so far? I'd suggest starting with Import-Csv then using foreach-object to perform calculations Commented Jun 22, 2015 at 2:33
  • @jgreenwell i have tried this so far appended to the post Commented Jun 22, 2015 at 2:37
  • When you say "no luck", what output do you get? Commented Jun 22, 2015 at 3:25

1 Answer 1

2

It looks like you were really close. You just initialized $totaldisk wrong (and in the wrong place).

$coll = import-csv "C:\input.csv"
foreach ($record in $coll)
{
    $totaldisk =0
    for ($i=1; $i -lt 4; $i++)
    {

        $diskname = "disk"+$i
        $totaldisk += $record.$diskname
    }
    $totaldisk
 }
Sign up to request clarification or add additional context in comments.

4 Comments

I know I've done with Measure-Object and select but I'm far too tired to remember how apparently, so +1 to you.
The problem with measure-object is that it looks at properties across objects rather than within objects (if that makes sense). It could sum all the disk1's together and so on, but not disk1+disk2...
yeah, I must just be way too tired.
@AnsgarWiechers Done now. Was new to this forum and was not aware how to mark as accepted earlier.

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.