0

I'm writing a script and have been running into the error described in the title. My code is below. I've tried even outputting "$i" and it shows the expected values, so I'm not sure why it is giving me the error. When it gets to the "Write-Host" line, it doesn't even output it. What am I missing?

$LogName = @() #Declaration of an empty array

$NumberOfLogs = Read-Host -Prompt "How many logs do you want to retrieve?" 
for ($i=0
$i -lt $NumberOfLogs
$i++) 
{ 
$j = $i+1
$LogName[$i] = Read-Host -Prompt "Enter name of Log #$j"
Write-Host $LogName[$i]
}

Apparently there is another post about this, but I tried the suggestion listed as the answer it still gives me the same error.

Joseph
  • 609
  • 2
  • 12
  • 26
  • Did you expect something else from empty array? Empty array does not have any valid index to write to or read from. – user4003407 Feb 17 '16 at 20:23
  • Possible duplicate of [PowerShell array initialization](http://stackoverflow.com/questions/226596/powershell-array-initialization) – dotnetom Feb 17 '16 at 20:34
  • I thought I was entering something into the array at the "$LogName[$I] = Read-Host..." line? – Joseph Feb 17 '16 at 20:35
  • @dotnetom I looked at the post you mentioned and it suggests adding the element using the += operator, which I tried and it gave me the same error. – Joseph Feb 17 '16 at 20:41

2 Answers2

2

The correct answer is to initialize the array in a different way that is posted on most powershell websites. Even the post that dotnetom suggested didn't have it as the main answer, but as a comment on the main answer. Either way, the correct way to do it is as follows:

$NumberOfLogs = Read-Host -Prompt "Enter the number of logs you want"
$LogName = New-Object string[] $NumberOfLogs

Then the rest of my for loop worked fine.

Joseph
  • 609
  • 2
  • 12
  • 26
0

PowerShell arrays are a fixed size. Since it was created with a length of zero, trying to add anything to it results in the error.

There are of course numerous ways to address this, but probably the easiest way in this case is to use an arraylist, which is more flexible, instead of an array:

$LogName = new-object system.collections.arraylist
Tony Hinkle
  • 4,706
  • 7
  • 23
  • 35