Powershell 输入管道问题
Powershell input piping issue
我无法运行这个简单的 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".
你不能像那样索引到 $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"
如果您这样检查 $input
:
PS> function f { $input.GetType().FullName } f
System.Collections.ArrayList+ArrayListEnumeratorSimple
那么你可以注意到,$input
不是一个集合,而是一个枚举器。因此,您无法使用 bare $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]
我无法运行这个简单的 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".
你不能像那样索引到 $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"
如果您这样检查 $input
:
PS> function f { $input.GetType().FullName } f
System.Collections.ArrayList+ArrayListEnumeratorSimple
那么你可以注意到,$input
不是一个集合,而是一个枚举器。因此,您无法使用 bare $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]