Home > other >  How do I make an array of arrays? or list of arrays in powershell?
How do I make an array of arrays? or list of arrays in powershell?

Time:04-22

enter image description here

$Colors = @{
1         =   'White'               
2         =   'Black'         
3         =   'DarkBlue'    
4         =   'DarkGreen'     
5         =   'DarkCyan'      
6         =   'DarkRed'       
7         =   'DarkMagenta'   
8         =   'DarkYellow'    
9         =   'Gray'          
10        =   'DarkGray'      
11        =   'Blue'          
12        =   'Green'         
13        =   'Cyan'          
14        =   'Red'           
15        =   'Magenta'       
16        =   'Yellow'         
                 
        }

$pixels = 1,2,3,4,5,6
         
foreach ($pixel in $pixels)
{
  Write-Host " " -NoNewline -BackgroundColor $Colors.$pixel
}

I have this code above that I am trying to use to draw pixelated images in the powershell window. Right now it is set up to just draw that single row of pixels. I am wondering how I can either make a list of lists, or array of arrays, or list of arrays that I can use to draw out a 20x20 pixel size image for example. I am familiar with how to do this in python but not powershell, something like shown below. A multidimensional array of sorts or something.

$pixels = [(1,2,3,4,5,6)],
          [(6,5,4,3,2,1)]
         
foreach ($pixel in $pixels)
{
  Write-Host " " -NoNewline -BackgroundColor $Colors.$pixel
}

Upon doing more research I found something like below that might work but I do not know how to iterate through it correctly

System.Collections.ArrayList]$pixels = @()
$pixels = @(@(1,2,3),@(4,5,6),@(7,8,9))
         
foreach ($pixel in $pixels){ Write-Host "  " -NoNewline -BackgroundColor $Colors.$pixel; Start-Sleep -m 50 }

CodePudding user response:

You can still create a multi-dimensional array, but of course you must still loop over each individual array, and loop again for every element in each array.

I think you're only missing an inner-loop and new line in your code:

$Colors = @{
    1         =   'White'               
    2         =   'Black'         
    3         =   'DarkBlue'    
    4         =   'DarkGreen'     
    5         =   'DarkCyan'      
    6         =   'DarkRed'       
    7         =   'DarkMagenta'   
    8         =   'DarkYellow'    
    9         =   'Gray'          
    10        =   'DarkGray'      
    11        =   'Blue'          
    12        =   'Green'         
    13        =   'Cyan'          
    14        =   'Red'           
    15        =   'Magenta'       
    16        =   'Yellow'         
}

$arrays = @(1,2,3,4,5,6), @(6,5,4,3,2,1)
         
foreach ($array in $arrays)
{
  foreach ($position in $array) {
    Write-Host " " -NoNewline -BackgroundColor $Colors[$position]
  }
  Write-Host ""
}
  • Related