问题
No matter how I write this script, Powershel will not write my array as it should, it prints a single line array.
PS C:\Windows\system32> $matriz = @(
(1,2,3,4),
(5,6,7,8)
)
Write-Host $matriz
1 2 3 4 5 6 7 8
Neither this way:
PS C:\Windows\system32> $matriz = ,@((1,2,3,4),
(5,6,7,8))
Write-Host $matriz
1 2 3 4 5 6 7 8
How do I print this as a real 2-dimension matrix?
And... I'm trying to populate this same array with Get-Random
, but it shows the following error: Failed add the number where you want (i.e. matriz [0,1]) because it doesn't support fractions
<- Not the real message but you guys won't understand portuguese :/
*Update:
I want it to be printed as this:
1 2 3 4
5 6 7 8
'Cause the single line thing won't help me to see if my matrix is correct, as a single line I will never know what is in the array's diagonal line.
回答1:
So when you output an array, powershell by default outputs each array item on a new line. Here is one way to get what I think you want:
Write-Host $matriz | %{$_ -join ' '}
So you tell it to go ahead and use the new line for the outside array, but for each of the inside arrays join them using spaces.
回答2:
That is how a two dimensional array prints. If you want to display it in some other way, you'll need to format it yourself:
$matriz = @((1,2,3,4),(5,6,7,8))
$matriz | ForEach-Object {
$_ | ForEach-Object {
Write-Host ("{0,5}" -f $_) -NoNewline;
}
Write-Host;
}
You're also not calling matrix elements correctly. $matriz[1,1]
, for example, actually means (,$matriz[1] + ,$matriz[1])
. That's because 1,1
is itself an array.
What you'd need to do to properly find single elements is to use multiple indexes: $matriz[1][1]
回答3:
This uses a trick but will make it print in two lines:
$matriz = ,@(1,2,3,4)+,@(5,6,7,8)
$matriz | % {Write-Host $_ }
Output is:
1 2 3 4
5 6 7 8
Each item can be individually referenced as $matriz[x][y]
where x,y are the sizes of the two dimentional array (As Bacon said).
来源:https://stackoverflow.com/questions/27608099/array-in-powershell-wont-be-written-as-an-array