3

Displaying Contents and Structure of an array

PS C:\> $a = 1,2,3
PS C:\> $b = 4,5,6
PS C:\> $c = $a,$b
PS C:\> $c
1
2
3
4
5
6

$c is not an array of numbers, it's an array of arrays. But when I display its contents, this structure is not visible.

Is there any built-in way to display the contents of an array such that the structure is preserved? Perhaps something like this:

@( @(1, 2, 3), @(4, 5, 6) )
PortMan
  • 4,205
  • 9
  • 35
  • 61
  • 1
    Your current code doesn't create an array of arrays. Powershell will "fix it for you", and make `$c` a single concatenated array. See http://stackoverflow.com/questions/11138288/how-to-create-array-of-arrays-in-powershell?rq=1 – Eris May 04 '16 at 21:00
  • 1
    `Format-Custom -InputObject $c -Expand CoreOnly` – user4003407 May 04 '16 at 21:21
  • @Eris You are not right. OP code really create array of arrays. – user4003407 May 04 '16 at 21:22

1 Answers1

2

The built-in way to display is as PetSerAl answered in the comments is to use Format-Custom cmdlet. It formats the output using a default or customized view. Read more at MSDN

Code (as answered by PetSerAl) is:

Format-Custom -InputObject $c -Expand CoreOnly

In case you want the display in the format you have mentioned exactly, then you need to write your own PowerShell code snippet. Note that you can also write the same using Pipeline. I expanded in favor of readability.

$a = 1,2,3
$b = 4,5,6
$c = $a,$b

$arrayForDisplay = "@( "
foreach($array in $c)
{
    $arrayForDisplay += "@( "
    foreach($arrayelement in $array)
    {
        $arrayForDisplay += $arrayelement.ToString() + ","
    }

    $arrayForDisplay = $arrayForDisplay -replace ".$"
    $arrayForDisplay += " ), "
}
$arrayForDisplay = $arrayForDisplay.Trim() -replace ".$"
$arrayForDisplay += " )"

$arrayForDisplay
Aman Sharma
  • 1,930
  • 1
  • 17
  • 31