Powershell 以表格格式显示二维数组

Powershell 以表格格式显示二维数组,powershell,Powershell,我正在学习一点图论,并转向Powershell文本格式。我正在编写一个脚本,它根据用户输入创建一个二维数组,并以表格格式显示该数组。第一部分很简单:询问用户数组的大小,然后询问用户每个元素的值。第二部分——在行和列中显示数组——很困难 Powershell在其自己的行中显示阵列的每个元素。以下脚本生成以下输出: $a= ,@(1,2,3) $a+=,@(4,5,6) $a 1 2 3 4 5 6 我需要像这样的输出: 1 2 3 4 5 6 我可以使用scriptblocks正确设置其格式

我正在学习一点图论,并转向Powershell文本格式。我正在编写一个脚本,它根据用户输入创建一个二维数组,并以表格格式显示该数组。第一部分很简单:询问用户数组的大小,然后询问用户每个元素的值。第二部分——在行和列中显示数组——很困难

Powershell在其自己的行中显示阵列的每个元素。以下脚本生成以下输出:

$a= ,@(1,2,3)
$a+=,@(4,5,6)
$a

1
2
3
4
5
6
我需要像这样的输出:

1 2 3
4 5 6
我可以使用scriptblocks正确设置其格式:

"$($a[0][0])   $($a[0][1]) $($a[0][2])"
"$($a[1][0])   $($a[1][1]) $($a[1][2])"

1   2   3
4   5   6
但这只有在我知道数组大小的情况下才有效。大小由用户在每次运行脚本时设置。它可能是5x5或100x100。 我可以使用foreach循环调整行数:

foreach ($i in $a){
     "$($i[0]) $($i[1]) $($i[2])"
     }
foreach ($i in $a){
     foreach($j in $i){
          $j
          }
     }
但是,这不会根据列数进行调整。我不能只嵌套另一个foreach循环:

foreach ($i in $a){
     "$($i[0]) $($i[1]) $($i[2])"
     }
foreach ($i in $a){
     foreach($j in $i){
          $j
          }
     }
只需在其自己的行上再次打印每个元素。嵌套的foreach循环是我用来遍历数组中每个元素的方法,但在这种情况下,它们对我没有帮助。有什么想法吗

目前的脚本如下所示:

clear

$nodes = read-host "Enter the number of nodes."

#Create an array with rows and columns equal to nodes
$array = ,@(0..$nodes)
for ($i = 1; $i -lt $nodes; $i++){
     $array += ,@(0..$nodes)
     }

#Ensure all elements are set to 0
for($i = 0;$i -lt $array.count;$i++){
     for($j = 0;$j -lt $($array[$i]).count;$j++){
          $array[$i][$j]=0
          }
     }

#Ask for the number of edges
$edge = read-host "Enter the number of edges"

#Ask for the vertices of each edge
for($i = 0;$i -lt $edge;$i++){
     $x = read-host "Enter the first vertex of an edge"
     $y = read-host "Enter the second vertex of an edge"
     $array[$x][$y] = 1
     $array[$y][$x] = 1
     }

#All this code works. 
#After it completes, I have a nice table in which the columns and rows 
#correspond to vertices, and there's a 1 where each pair of vertices has an edge.
此代码生成一个邻接矩阵。然后我可以使用矩阵来学习所有关于图论算法的知识。同时,我想让Powershell将其显示为一个整洁的小桌子。有什么想法吗

试试这个:

$a | % { $_ -join ' ' }
或者更好

$a | % { $_ -join "`t" }

成功了。非常感谢你。