2016-12-03 60 views
0

我不能夠運行這個簡單的PowerShell程序PowerShell的輸入管道問題

[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" 

我試圖像這樣

120,130,90,45,30輸入管道運行| \ sample_program.ps1

我一直收到此錯誤

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

'$ InputArray = @($輸入); [int] $ st1 = $ InputArray [0]; ...' – PetSerAl

+0

@PetSerAl ...這是正確的,但爲什麼在評論? :)請移動它回答,以便我可以標記它是正確的:) –

回答

1

如果檢查$input這樣的:

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

然後你可以看到,$input不是一個集合,而是一個枚舉器。因此,您沒有使用索引器隨機訪問$input。如果你真的想要索引$input,則需要將其內容複製到陣列或一些其他集合:

$InputArray = @($input) 

那麼你可以索引$InputArray正常:

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

你不能索引$input這樣。

您可以利用ForEach-Object

$st1,$st2,$st3,$pm,$cm = $input |ForEach-Object { $_ -as [int] } 

或(最好),命名參數:

param(
    [int]$st1, 
    [int]$st2, 
    [int]$st3, 
    [int]$pm, 
    [int]$cm 
) 

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

這一個工程,但我會與@PetSalAl的迴應,它有點整齊 –