用于读取不同值的数组

时间:2017-05-15 13:18:33

标签: arrays powershell

如何在PowerShell中输入多个值并将这些值存储在变量中?

例如:

$value = Read-Host "Enter the value's" #I need 15 values to be entered.

然后回想起来,例如:

$value[0] = 1233
$value[1] = 2345

2 个答案:

答案 0 :(得分:2)

要执行此操作,您可以声明一个数组@(),然后使用循环和加法运算符将项添加到数组中(在提交空值时停止):

$values = @()

Do{
    $value = read-host "Enter a value"
    if ($value) {$values += $value}
}Until (-not $value)

然后,您可以通过带方括号[]的索引检索所描述的值:

$values       #returns all values
$values[3]    #returns the fourth value (if you entered four or more)

请注意,数组从0开始,因此第一项是[0],第二项是[1]等。使用PowerShell,您还可以使用负数来向后处理数组,因此{{1} }是最后一项,[-1]是倒数第二项,等等。

答案 1 :(得分:2)

将readin值存储在数组中:

$values = @()

$i = $null
while ($i -ne "q") {
    if ($i -ne $null) {
        # Attach value to array
        $values += $i
    }
    $i = Read-Host "Enter value (stop with q)"
}

# Print each value in a seperate line
$values | % { Write-Host $_}
# Print type -> to visualize that it is an array
$values.GetType()

# Several values can be retrieved via index operator
$values[0]