Search code examples
powershellpiping

Powershell input piping issue


I am not able to run this simple powershell program

[int]$st1 = $input[0]
[int]$st2 = $input[1]
[int]$st3 = $input[2]
[int]$pm = $input[3]
[int]$cm = $input[4]

$MedMarks = $st1 + $st2 + $st3 - ($pm + $cm)
Write-Host "Med Marks  $MedMarks"

I am trying to run it with input pipeline like this

120, 130, 90, 45, 30 | .\sample_program.ps1

I am consistently getting this error

Cannot convert the "System.Collections.ArrayList+ArrayListEnumeratorSimple" value of type
"System.Collections.ArrayList+ArrayListEnumeratorSimple" to type "System.Int32".

Solution

  • If you inspect $input like this:

    PS> function f { $input.GetType().FullName } f
    System.Collections.ArrayList+ArrayListEnumeratorSimple
    

    then you can notice, that $input is not a collection, but an enumerator for one. So, you do not have random access with indexer for bare $input. If you really want to index $input, then you need to copy its content into array or some other collection:

    $InputArray = @( $input )
    

    then you can index $InputArray as normal:

    [int]$st1 = $InputArray[0]
    [int]$st2 = $InputArray[1]
    [int]$st3 = $InputArray[2]
    [int]$pm = $InputArray[3]
    [int]$cm = $InputArray[4]