簡體   English   中英

包含數組的Powershell數組

[英]Powershell array containing array

我正在學習PowerShell(新手警報!!)並試圖弄清楚為什么會出現以下奇怪的行為。 (環境:帶有PowerShell 5的Windows 10)

C:\>POWERSHELL
Windows PowerShell
Copyright (C) 2015 Microsoft Corporation. All rights reserved.

PS > $A=(1,2,3) # When a variable stores a new array, ...
PS > $A # the elements are shown correctly.
1
2
3
PS > $B=$A # When the array is copied, ...
PS > $B # the elements are shown correctly.
1
2
3
PS > $B=($A,4,5,6) # When the variable stores a new array with elements from some other array ...
PS > $B # the elements are shown correctly.
1
2
3
4
5
6
PS > $B=($B,7,8,9) # But, when the variable stores a new array with elements from the array currently stored in the same variable, ...
PS > $B # something strange is seen


Length         : 3
LongLength     : 3
Rank           : 1
SyncRoot       : {1, 2, 3}
IsReadOnly     : False
IsFixedSize    : True
IsSynchronized : False
Count          : 3

4
5
6
7
8
9


PS >

有關正在發生的事情的任何指示?

在輸入這個問題時,我試圖分析這種情況。 我看待它的方式:
$B=($A,4,5,6)使$ B成為一個帶數組元素的數組。
$B=($B,7,8,9)使$ B成為一個帶有數組元素的數組元素的數組。
顯示變量內容的PowerShell CLI函數不會一直向下到葉元素,而是在第二級停止。
因此,最內部的數組(contents == $ A)顯示為某個對象。
這個解釋是否正確?

原因是PowerSer Just inflat one level。 所以,只需看看以下結果即可了解:

$B[0] -> 1,2,3,4,5,6
$B[0][0] -> 1,2,3 # Your $A
$b[0][0][0] -> 1 # Etc ...
$B[0][1] -> 4
$B[0][2] -> 5
$B[1] -> 7
$B[2] -> 8
$B[3] -> 9

如果你想要一個多維數組盡管有陣列數組,你可以使用:

$arrayAll = New-Object 'int[,]' (3,3)
$arrayAll[2,0] = 42

經過進一步分析(以及來自tire0011和Mathias R. Jessen和JPBlanc的輸入)后,情況變得更加清晰。

這個問題分為兩部分:
(A)數據是否以某種奇怪的格式存儲(甚至被破壞)?
(B)如果沒有,為什么輸出沒有顯示從1到9的數字?

PS > ConvertTo-Json -InputObject $B
[
    [
        [
            1,
            2,
            3
        ],
        4,
        5,
        6
    ],
    7,
    8,
    9
]
PS >

(A)數據正確存儲在“數組內部數組”格式中,沒有任何損壞。
(B)PowerShell CLI輸出僅顯示2個級別的內容,並顯示更深層次的對象。 我找不到這個說法的參考,但我最接近的是: https//technet.microsoft.com/en-us/library/hh849922.aspx

-Depth<Int32>
    Specifies how many levels of contained objects are included in the JSON representation.
    The default value is 2.

如果我在CLI輸出中獲得“深度”的引用,我將更新此答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM