简体   繁体   中英

My script is giving the error “Index was outside bounds of array” Powershell

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM