Powershell 2d array foreach loop [duplicate]

Currently I have a for each in a function. When I call it in 2 different scenarios is wierd.

If the 2d array has multiple and ask for the first slot of each then it outputs correctly.

for example:

$packManagers = @( # (Name, executable, Path)
    @("PowerShell Core", "pwsh", "Microsoft.Powershell"),
    @("Git", "git", "Git.Git"),
    @("NVM", "nvm", "CoreyButler.NVMforWindows"),
    @("Python", "py", "Python3")

Output

- Powershell Core
- Git
- NVM
- Python

but when I outputed only one value then it start going through all the items inside the only one and getting the first character.
For example:

$packScoop = @( # (Name, executable, Path)
    @("Scoop", "scoop", "get.scoop.sh")
)

Output

- S
- s
- g

I as well tried with the following to do some testing and the output was different than expected.

code:

foreach ($curr in @(@("HI", "Bi", "Try"))) {
    Write-Host "$($curr[0]) - $($curr[1]) - $($curr[2])"
}

Expected:

HI - Bi - Try

Actual:

H - I - 
B - i -
T - r - y

  • What is a $curr?

    – 

  • You hit one of the most common gothas of PowerShell

    – 

Collections of collections created with a single item are often squished(others will most likely going to explain you why)

If you are MAKING a single-item array: instead of @(@(<#content#>)) use ,@(<#content#>)

foreach ($curr in ,@("HI", "Bi", "Try")) {
    Write-Host "$($curr[0]) - $($curr[1]) - $($curr[2])"
}

though I suggest to get used into using List instead of arrays as they resolve a lot of issues.

I found a way to fix it. So powershell with arrays when there is only one present element in an array then it interpets it implicitly as non nested arrays.

For Example:

$arr1 = @("Hi", "Bye")
Write-Host $arr1

$arr2 = @("Hi")
Write-Host $arr2

Output:

Object[] -> Array type
String

To fix this you need to add a comma in the beggining

Example:

$arr2 = @(,"Hi")
Write-Host $arr2

Output:

Object[] -> Type Array

Leave a Comment