动态输入数组Powershell

时间:2012-12-07 13:28:33

标签: powershell

我再次与您联系,因为我再次遇到Powershell脚本分配问题。 我目前的任务是创建一个脚本,让用户输入1-10个值。值必须是正数。之后我必须计算一个数组的平均值。

我的想法如下:

clear-host  
$averageArray = @()

Write-Host "How many numbers do you want to put in?" -for yellow
Write-Warning "Maximum is 10!"
Write-Host "Press the Enter key to continue."

$amountValues = Read-host
while($amountVAlues -notmatch "^([1-9]|[1][0])$") {
   $amountValues = Read-Host "Please enter a number between 1 and 10"

if($amountVAlues -notmatch "^([1-9]|[1][0])$") {Write-host "Error! Please enter a number between 1 and 10!"}
} 

$value1 = read-host "Enter number one"

while($value1 -notmatch '^\d+$') {
   $value1 = Read-Host 
if($value1 -notmatch '^\d+$') {Write-host "Error! Please enter a positive number!"}
} 

$value2 = read-host "Enter number two"

while($value2 -notmatch '^\d+$') {
   $value2 = Read-Host 
if($value2 -notmatch '^\d+$') {Write-host "Error! Please enter a positive number!"}
} 


$averageArray = $averageArray + $value1

write-host "$averageArray"


read-host

我创建了一个数组,并为用户输入了1-10之间的数字,表示他们想要在数组中获得的总$值。之后我想循环输入$ value,并将其输入数组。我想循环它和$ amountValues变量一样多次。

这样做的问题是,如果我循环它,$ variable1会被覆盖'x'次。

有没有办法通过循环将值输入数组?

1 个答案:

答案 0 :(得分:5)

我这样做:

while ( (1..10) -notcontains $g)
{
    $g = read-host "How many numbers do you want to put in? (value from 1 to 10) " 
}    
$ar=@()
for ($i=0; $i -lt $g; $i++)
{
   $ar += read-host "Enter value $($i+1)"
}    
$averageArray = ($ar | Measure-Object -Average).average    
write-host "Average is : $averageArray"