如何在PowerShell中创建数组?

时间:2022-03-29 12:53:09

I want to create an array of arrays in powershell.

我想在PowerShell中创建一个数组数组。

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

Works fine. However, sometimes I have only one array in the array list. In that situation, powershell ignores one of the lists:

工作正常。但是,有时我在数组列表中只有一个数组。在那种情况下,powershell会忽略其中一个列表:

$x = @(
    @(1,2,3)
)

$x[0][0] # Should return 1
Unable to index into an object of type System.Int32.
At line:1 char:7
+ $a[0][ <<<< 0]
    + CategoryInfo          : InvalidOperation: (0:Int32) [], RuntimeException
    + FullyQualifiedErrorId : CannotIndex

How do I create an array of arrays, guaranteed it's remain as a two-dimension array even if the array has only one array item in it?

如何创建一个数组数组,保证它仍然是一个二维数组,即使数组中只有一个数组项?

1 个解决方案

#1


33  

Adding a comma force to create an array:

添加逗号力以创建数组:

$x = @(
    ,@(1,2,3)
)

Simple way:

简单方法:

$x = ,(1,2,3)

#1


33  

Adding a comma force to create an array:

添加逗号力以创建数组:

$x = @(
    ,@(1,2,3)
)

Simple way:

简单方法:

$x = ,(1,2,3)