Search code examples
arraysexcelfor-looparraylistpowershell-4.0

how to create bunch of arrays inside a loop in powershell


I'm writing a script to fetch values for a set of components and storing the fetched values in an array. As there are many components I created a loop and tried to create an array name along with its iteration value (fi1, fi2, fi3, etc.) like this.

Here is the code:

function fiswitchinfo {
    Param ($sheet, [string]$text, $iter)

    $($fi+($iter)) = @()
    $max = $sheet.UsedRange.Rows.Count
    for ($i=1; $i -lt 900 ; $i++) {
        $rows = $sheet.Cells.Item($i, 2).EntireRow
        $cell_info = $sheet.Cells.Item($i, 2)
        $cell = $cell_info.Address($false, $false)
        if ($rows.hidden -eq $false) {
            $cell_info = $sheet.Cells.Item($i, 2).Text

            if ($cell_info -ne "" -and $cell_info.Contains($text) -eq "True") {
                $cell = $cell -split "(?<=[A-Z])(?=\d)"
                [int]$curline =  $cell[1]
                $component = $sheet.Cells.Item($curline, 2).Text
                $compip = $sheet.Cells.Item($curline, 3).Text

                $row = $sheet.Cells.Item($curline, 2).EntireRow
                $cellinfo = $sheet.Cells.Item($curline, 2).text
                if ($row.Hidden -ne "True" -and $cellinfo -ne $null) {
                    Write-Host $component $compip
                    $script:fi+$iter += $compip
                }
            }
        }
    }
}

fiswitchinfo $worksheet_3 "Fabric Interconnect 01 Cluster IP" 1
fiswitchinfo $worksheet_3 "Fabric Interconnect 01 A" 1
fiswitchinfo $worksheet_3 "Fabric Interconnect 01 B" 1

Solution

  • I'm not quite sure what you expect $($fi+($iter)) or $script:fi+$iter to do, but I'm pretty certain they won't do whatever it is you expect.

    To have a function create an array of arrays in a loop and then return it you'd do something like this:

    function fiswitchinfo {
        ...
        $arr = @()
        for ($i=1; $i -lt 900 ; $i++) {
            ...
            $arr += ,$compip
        }
        return ,$arr
    }
    
    $fi1 = fiswitchinfo ...
    $fi2 = fiswitchinfo ...
    ...
    

    The leading comma in the statements $arr += ,$compip and return ,$arr is the unary array construction operator, which prevents PowerShell from unrolling the arrays. $arr += ,$compip appends $compip to $arr as a nested array (thus making $arr a jagged array) instead of appending the elements of $compip to $arr. return ,$arr ensures that $arr is returned to the caller as-is (thus preserving the array even if it's empty).