1

I want to add some data into one array variable in PowerShell. but it is showing error like "Index was outside the bounds of the array". What I have is:

$test = @()
for ($i = 0 ; $i -lt 20; $i++)
{
    $test[$i] = $i
}
$test

And it is showing error that "Index was outside the bounds of the array".

Is there any way in PowerShell to store the data into an array variable.

2 Answers 2

3

$test = @() is a dynamically sized array. If you want to use that you need to append to it in the loop:

$test = @()
for ($i = 0 ; $i -lt 20; $i++) {
    $test += $i
}

or (better):

$test = @(for ($i = 0 ; $i -lt 20; $i++) {
    $i
})

or (even better, at least in this particular scenario):

$test = 0..19

If you want to assign values via indexed access you need to define the array with a fixed size:

$test = New-Object Object[] (20)
for ($i = 0 ; $i -lt 20; $i++) {
    $test[$i] = $i
}

or pre-load a dynamically sized array with the desired number of elements:

$test = 1..20 | ForEach-Object { $null }
for ($i = 0 ; $i -lt 20; $i++) {
    $test[$i] = $i
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try this -

$test = @()
for($i = 0 ; $i -lt 20; $i++)
{
    $test += $i
}
$test

$test[$i] is one of the elements of the array and obviously if you are trying to store 20 elements there, it is bound to give you ArrayOutOfBounds exception. Use the += operator to add values to an existing array. After you are done storing the elements, you can access individual elements of the array like $test[0]..$test[19] (since an array's index start from 0).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.