简体   繁体   English

Powershell输入管道问题

[英]Powershell input piping issue

I am not able to run this simple powershell program 我无法运行此简单的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"

I am trying to run it with input pipeline like this 我正在尝试使用这样的输入管道运行它

120, 130, 90, 45, 30 | 120、130、90、45、30 | .\\sample_program.ps1 \\ 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".

You can't index into $input like that. 您不能像这样索引$input

You can utilize ForEach-Object : 您可以利用ForEach-Object

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

or (preferably), use named parameters: 或(最好)使用命名参数:

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

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

If you inspect $input like this: 如果您像这样检查$input

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. 那么您会注意到, $input不是集合,而是一个枚举器。 So, you do not have random access with indexer for bare $input . 因此,您没有使用indexer进行裸$input随机访问。 If you really want to index $input , then you need to copy its content into array or some other collection: 如果您真的想索引$input ,则需要将其内容复制到数组或其他集合中:

$InputArray = @( $input )

then you can index $InputArray as normal: 那么您可以像$InputArray一样索引$InputArray

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM