Dusty Vargas
Dusty Vargas

Reputation: 945

Powershell for loop throwing "the array index evaluated to null"

For starters, I'm on Fedora 30 using PSCore version 6.2.1. I've encountered this issue in GNOME Terminal and the vscode snap.

I'm on the first challenge of the PSKoans module and I'm stuck when trying to use a for loop. I am given an array of strings, each of which is a collection of strings separated by commas.

$StockData = @(
    "Date,Open,High,Low,Close,Volume,Adj Close"
    "2012-03-30,32.40,32.41,32.04,32.26,31749400,32.26"
    "2012-03-29,32.06,32.19,31.81,32.12,37038500,32.12"
) # The array is much longer than that, but shortened for simplicity's sake

So, my idea is to build a hashtable out of each subsequent string line in the array by using the first string in the array as keys and each following line as a set of values. I'm using -split to split the values apart from within the strings. I want to use a for loop to iterate through the array and pull values, building a hastable in a file to be read later like so:

# Build the array of keys
[array]$keys = $StockData[0] -split ','
# Begin for loop, using $i as int
for ($i = 1, $StockData[$i], $i++) {
    # Create a text file for each hastable
    New-Item -Name "ht$i.txt" -ItemType File
    # Split current string into values
    $values = $StockData[$i] -split ','
    # Set value int
    $valuesInt = 0
    foreach ($key in $keys) {
        Add-Content -Path "./ht$i.txt" -Value "$key = $values[$valuesInt]"
        $valuesInt++
    }
}

As I run that, I get the following error:

Index operation failed; the array index evaluated to null.
At /home/user/PSKoans/Foundations/SolutionStockChallenge.ps1:28 char:6
+ for ($i = 1, $stockData[$i], $i++) {
+      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArrayIndex

I've looked it up and I find all kinds of scenarios in which people get this error message. I didn't really find a solid explanation for the error message the might lead me to an answer.

Reading the error message, it doesn't make sense to me. the array index evaluated to null...but the array index in the first case is $StockData[1] which is a valid index and should return $true and continue with the loop. Am I missing something?

Upvotes: 1

Views: 2986

Answers (2)

codersl
codersl

Reputation: 2332

The syntax of your for loop is wrong. The for loop uses semi-colons as separators.

for ($i = 1, $StockData[$i], $i++) {

should be

for ($i = 1; $StockData[$i]; $i++) {

Upvotes: 2

Axel Andersen
Axel Andersen

Reputation: 1128

ConvertFrom-Json in PowerShell Core has the coolest switch - AsHashTable. Try this:

$StockData | convertfrom-csv | convertto-json | ConvertFrom-Json -AsHashtable

Upvotes: 0

Related Questions