关于数组About Arrays

简短说明Short Description

介绍数组,数组是设计用于存储项集合的数据结构。Describes arrays, which are data structures designed to store collections of items.

详细说明Long Description

数组是一种数据结构,用于存储项的集合。An array is a data structure that is designed to store a collection of items. 项可以是同一类型,也可以是不同的类型。The items can be the same type or different types.

从 Windows PowerShell 3.0 开始,零个或一个对象的集合具有数组的某些属性。Beginning in Windows PowerShell 3.0, a collection of zero or one object has some properties of arrays.

创建和初始化数组Creating and initializing an array

若要创建并初始化数组,请将多个值分配给一个变量。To create and initialize an array, assign multiple values to a variable. 存储在数组中的值用逗号分隔,赋值运算符将其与变量名称隔开 (=) 。The values stored in the array are delimited with a comma and separated from the variable name by the assignment operator (=).

例如,若要创建一个名为 $A 的数组,该数组包含七个数值 (int) 值22、5、10、8、12、9和80,请键入:For example, to create an array named $A that contains the seven numeric (int) values of 22, 5, 10, 8, 12, 9, and 80, type:

$A = 22,5,10,8,12,9,80

还可以通过将逗号置于单个项之前来初始化单个项数组。The comma can also be used to initialize a single item array by placing the comma before the single item.

例如,若要创建名为 $B 包含单值7的单个项数组,请键入:For example, to create a single item array named $B containing the single value of 7, type:

$B = ,7

还可以通过使用范围运算符 () 来创建和初始化数组 ..You can also create and initialize an array by using the range operator (..). 下面的示例创建一个包含值5到8的数组。The following example creates an array containing the values 5 through 8.

$C = 5..8

因此, $C 包含四个值:5、6、7和8。As a result, $C contains four values: 5, 6, 7, and 8.

如果未指定数据类型,则 PowerShell 会将每个数组作为对象数组创建 ( system.object [] ) 。When no data type is specified, PowerShell creates each array as an object array ( System.Object[] ). 若要确定数组的数据类型,请使用 GetType ( # B1 方法。To determine the data type of an array, use the GetType() method. 例如,若要确定数组的数据类型 $A ,请键入:For example, to determine the data type of the $A array, type:

$A.GetType()

若要创建强类型化数组(即,只可包含特定类型的值的数组),请将该变量强制转换为数组类型,如 string []long []int32 []To create a strongly typed array, that is, an array that can contain only values of a particular type, cast the variable as an array type, such as string[] , long[] , or int32[] . 若要强制转换数组,请在变量名称之前加上括号内的数组类型。To cast an array, precede the variable name with an array type enclosed in brackets. 例如,若要创建一个名为的32位整数数组,该数组 $ia 包含四个整数 (1500、2230、3350和 4000) ,请键入:For example, to create a 32-bit integer array named $ia containing four integers (1500, 2230, 3350, and 4000), type:

[int32[]]$ia = 1500,2230,3350,4000

因此, $ia 数组只能包含整数。As a result, the $ia array can contain only integers.

你可以创建在 Microsoft .NET 框架中强制转换为任何支持的类型的数组。You can create arrays that are cast to any supported type in the Microsoft .NET Framework. 例如, Get-Process 检索以表示进程的对象属于 system.object 类型。For example, the objects that Get-Process retrieves to represent processes are of the System.Diagnostics.Process type. 若要创建进程对象的强类型数组,请输入以下命令:To create a strongly typed array of process objects, enter the following command:

[Diagnostics.Process[]]$zz = Get-Process

数组子表达式运算符The array sub-expression operator

"数组" 子表达式运算符从它内部的语句创建一个数组。The array sub-expression operator creates an array from the statements inside it. 如果运算符中的语句生成,运算符会将其放在数组中。Whatever the statement inside the operator produces, the operator will place it in an array. 即使有零个或一个对象。Even if there is zero or one object.

数组运算符的语法如下所示:The syntax of the array operator is as follows:

@( ... )

可以使用 array 运算符创建零个或一个对象的数组。You can use the array operator to create an array of zero or one object. 例如:For example:

$a = @("Hello World")
$a.Count
1
$b = @()
$b.Count
0

当您获取对象时,array 运算符非常有用,但不知道您获取了多少个对象。The array operator is useful in scripts when you are getting objects, but do not know how many objects you get. 例如:For example:

$p = @(Get-Process Notepad)

有关数组子表达式运算符的详细信息,请参阅 about_OperatorsFor more information about the array sub-expression operator, see about_Operators.

访问和使用数组元素Accessing and using array elements

读取数组Reading an array

可以通过使用数组的变量名称来引用它。You can refer to an array by using its variable name. 若要显示数组中的所有元素,请键入数组名称。To display all the elements in the array, type the array name. 例如,假设 $a 是包含整数0、1、2和9的数组,则键入:For example, assuming $a is an array containing integers 0, 1, 2, until 9; typing:

$a
0
1
2
3
4
5
6
7
8
9

从位置0开始,可以使用索引引用数组中的元素。You can refer to the elements in an array by using an index, beginning at position 0. 将索引号括在括号中。Enclose the index number in brackets. 例如,若要显示数组中的第一个元素 $a ,请键入:For example, to display the first element in the $a array, type:

$a[0]
0

若要显示数组中的第三个元素 $a ,请键入:To display the third element in the $a array, type:

$a[2]
2

您可以使用索引的范围运算符来检索部分数组。You can retrieve part of the array using a range operator for the index. 例如,若要检索数组的第二到第五个元素,请键入:For example, to retrieve the second to fifth elements of the array, you would type:

$a[1..4]
1
2
3
4

负数从数组末尾开始计数。Negative numbers count from the end of the array. 例如,"-1" 指数组的最后一个元素。For example, "-1" refers to the last element of the array. 若要显示数组的最后三个元素,请在 "索引升序" 中键入:To display the last three elements of the array, in index ascending order, type:

$a = 0 .. 9
$a[-3..-1]
7
8
9

如果按降序键入负索引,则输出会发生变化。If you type negative indexes in descending order, your output changes.

$a = 0 .. 9
$a[-1..-3]
9
8
7

但是,使用此表示法时要格外小心。However, be cautious when using this notation. 表示法从结束边界到数组的开头。The notation cycles from the end boundary to the beginning of the array.

$a = 0 .. 9
$a[2..-2]
2
1
0
9
8

此外,一个常见错误是 $a[0..-2] 指引用数组的所有元素(最后一个元素除外)。Also, one common mistake is to assume $a[0..-2] refers to all the elements of the array, except for the last one. 它引用数组中的第一个、最后一个和第二个元素。It refers to the first, last, and second-to-last elements in the array.

您可以使用加号运算符 (+) 将范围与数组中的元素列表组合在一起。You can use the plus operator (+) to combine a ranges with a list of elements in an array. 例如,若要在索引位置0、2和4到6显示元素,请键入:For example, to display the elements at index positions 0, 2, and 4 through 6, type:

$a = 0 .. 9
$a[0,2+4..6]
0
2
4
5
6

此外,若要列出多个范围和单个元素,可以使用加号运算符。Also, to list multiple ranges and individual elements you can use the plus operator. 例如,若要列出元素0到2、4到6以及第8个位置的元素,请执行以下操作:For example, to list elements zero to two, four to six, and the element at eighth positional type:

$a = 0..9
$a[+0..2+4..6+8]
0
1
2
4
5
6
8

数组元素的迭代Iterations over array elements

你还可以使用循环构造,如 ForEach、For 和 While 循环,以引用数组中的元素。You can also use looping constructs, such as ForEach, For, and While loops, to refer to the elements in an array. 例如,若要使用 ForEach 循环显示数组中的元素 $a ,请键入:For example, to use a ForEach loop to display the elements in the $a array, type:

$a = 0..9
foreach ($element in $a) {
  $element
}
0
1
2
3
4
5
6
7
8
9

Foreach 循环会循环访问数组并返回数组中的每个值,直到到达数组的末尾。The Foreach loop iterates through the array and returns each value in the array until reaching the end of the array.

当您在检查数组中的元素时递增计数器时,For 循环非常有用。The For loop is useful when you are incrementing counters while examining the elements in an array. 例如,若要使用 For 循环来返回数组中的每个其他值,请键入:For example, to use a For loop to return every other value in an array, type:

$a = 0..9
for ($i = 0; $i -le ($a.length - 1); $i += 2) {
  $a[$i]
}
0
2
4
6
8

您可以使用 While 循环来显示数组中的元素,直至定义的条件不再为 true 为止。You can use a While loop to display the elements in an array until a defined condition is no longer true. 例如,若要在 $a 数组索引小于4的情况下显示数组中的元素,请键入:For example, to display the elements in the $a array while the array index is less than 4, type:

$a = 0..9
$i=0
while($i -lt 4) {
  $a[$i];
  $i++
}
0
1
2
3

数组属性Properties of arrays

Count 或 Length 或 LongLengthCount or Length or LongLength

若要确定数组中有多少项,请使用 Length 属性或其 Count 别名。To determine how many items are in an array, use the Length property or its Count alias. Longlength 如果数组包含的元素超过2147483647,则会很有用。Longlength is useful if the array contains more than 2,147,483,647 elements.

$a = 0..9
$a.Count
$a.Length
10
10

级别Rank

返回数组中的维数。Returns the number of dimensions in the array. PowerShell 中的大多数数组仅具有一个维度。Most arrays in PowerShell have one dimension, only. 即使您认为要生成多维数组,类似于以下示例:Even when you think you are building a multidimensional array; like the following example:

$a = @(
  @(0,1),
  @("b", "c"),
  @(Get-Process)
)

[int]$r = $a.Rank
"`$a rank: $r"
$a rank: 1

下面的示例演示如何使用 .Net Framework 创建一个真正的多维数组。The following example shows how to create a truly multidimensional array using the .Net Framework.

[int[,]]$rank2 = [int[,]]::new(5,5)
$rank2.rank
2

数组方法Methods of arrays

清除Clear

将所有元素值设置为数组元素类型的 默认值Sets all element values to the default value of the array's element type. Clear ( # A1 方法不会重置数组的大小。The Clear() method does not reset the size of the array.

在下面的示例中 $a ,是一个对象数组。In the following example $a is an array of objects.

$a = 1, 2, 3
$a.Clear()
$a | % { $null -eq $_ }
True
True
True

在此示例中, $intA 显式键入以包含整数。In this example, $intA is explicitly typed to contain integers.

[int[]] $intA = 1, 2, 3
$intA.Clear()
$intA
0
0
0

ForEachForEach

允许遍历数组中的所有元素,并为数组的每个元素执行给定操作。Allows to iterate over all elements in the array and perform a given operation for each element of the array.

ForEach 方法具有多个执行不同操作的重载。The ForEach method has several overloads that perform different operations.

ForEach(scriptblock expression)
ForEach(scriptblock expression, object[] arguments)
ForEach(type convertToType)
ForEach(string propertyName)
ForEach(string propertyName, object[] newValue)
ForEach(string methodName)
ForEach(string methodName, object[] arguments)

ForEach (scriptblock 表达式) ForEach(scriptblock expression)

ForEach (scriptblock 表达式,object [] 参数) ForEach(scriptblock expression, object[] arguments)

此方法是在 PowerShell v4 中添加的。This method was added in PowerShell v4.

备注

语法要求使用脚本块。The syntax requires the usage of a script block. 如果 scriptblock 是唯一的参数,则括号是可选的。Parentheses are optional if the scriptblock is the only parameter. 此外,在方法和左括号或大括号之间不得有空格。Also, there must not be a space between the method and the opening parenthesis or brace.

下面的示例演示如何使用 foreach 方法。The following example shows how use the foreach method. 在此示例中,目的是生成数组中元素的平方值。In this case the intent is to generate the square value of the elements in the array.

$a = @(0 .. 3)
$a.ForEach({ $_ * $_})
0
1
4
9

与的 -ArgumentList 参数一样 ForEach-Objectarguments 参数允许将参数数组传递到配置为接受它们的脚本块。Just like the -ArgumentList parameter of ForEach-Object, the arguments parameter allows the passing of an array of arguments to a script block configured to accept them.

有关 ArgumentList 行为的详细信息,请参阅 about_SplattingFor more information about the behavior of ArgumentList , see about_Splatting.

ForEach (类型 convertToType) ForEach(type convertToType)

ForEach方法可用于快速将元素强制转换为另一种类型; 下面的示例演示如何将字符串日期的列表转换为 [DateTime] 类型。The ForEach method can be used to swiftly cast the elements to a different type; the following example shows how to convert a list of string dates to [DateTime] type.

@("1/1/2017", "2/1/2017", "3/1/2017").ForEach([datetime])

Sunday, January 1, 2017 12:00:00 AM
Wednesday, February 1, 2017 12:00:00 AM
Wednesday, March 1, 2017 12:00:00 AM

ForEach (string propertyName) ForEach(string propertyName)

ForEach (string propertyName,object [] newValue) ForEach(string propertyName, object[] newValue)

ForEach方法还可用于快速检索或设置集合中每个项的属性值。The ForEach method can also be used to quickly retrieve, or set property values for every item in the collection.

# Set all LastAccessTime properties of files to the current date.
(dir 'C:\Temp').ForEach('LastAccessTime', (Get-Date))
# View the newly set LastAccessTime of all items, and find Unique entries.
(dir 'C:\Temp').ForEach('LastAccessTime') | Get-Unique
Wednesday, June 20, 2018 9:21:57 AM

ForEach (字符串方法名称) ForEach(string methodName)

ForEach (string 方法,object [] 参数) ForEach(string methodName, object[] arguments)

最后, ForEach 可使用方法对集合中的每个项执行方法。Lastly, ForEach methods can be used to execute a method on every item in the collection.

("one", "two", "three").ForEach("ToUpper")
ONE
TWO
THREE

与的 -ArgumentList 参数一样 ForEach-Objectarguments 参数允许将参数数组传递到配置为接受它们的脚本块。Just like the -ArgumentList parameter of ForEach-Object, the arguments parameter allows the passing of an array of arguments to a script block configured to accept them.

备注

从 Windows PowerShell 3.0 中开始,还可以使用 "标量对象和集合的方法" 来完成为集合中的每个项检索属性和执行方法的操作,可以在此处 about_methods获取详细信息。Starting in Windows PowerShell 3.0 retrieving properties and executing methods for each item in a collection can also be accomplished using "Methods of scalar objects and collections" You can read more about that here about_methods.

其中Where

允许筛选或选择数组的元素。Allows to filter or select the elements of the array. 脚本的计算结果必须为:零 (0) ,空字符串,或要 $false$null``WhereThe script must evaluate to anything different than: zero (0), empty string, $false or $null for the element to show after the Where

此方法有一个定义 WhereThere is one definition for the Where method.

Where(scriptblock expression[, WhereOperatorSelectionMode mode
                            [, int numberToReturn]])

备注

语法要求使用脚本块。The syntax requires the usage of a script block. 如果 scriptblock 是唯一的参数,则括号是可选的。Parentheses are optional if the scriptblock is the only parameter. 此外,在方法和左括号或大括号之间不得有空格。Also, there must not be a space between the method and the opening parenthesis or brace.

Expression是筛选所需的 scriptblock, mode 可选参数允许其他选择功能, numberToReturn 可选参数允许限制从筛选器返回的项数。The Expression is scriptblock that is required for filtering, the mode optional argument allows additional selection capabilities, and the numberToReturn optional argument allows the ability to limit how many items are returned from the filter.

的可接受值为 modeThe acceptable values for mode are:

  • 默认 (0) -返回所有项Default (0) - Return all items
  • 第一 (1) -返回第一项First (1) - Return the first item
  • 最后 (2) -返回最后一项Last (2) - Return the last item
  • 跳到 (3) -跳过项,直到 condition 为 true,返回剩余项SkipUntil (3) - Skip items until condition is true, the return the remaining items
  • 到 (4) 之前-返回所有项,直到 condition 为 trueUntil (4) - Return all items until condition is true
  • 拆分 (5) -返回两个元素组成的数组Split (5) - Return an array of two elements
    • 第一个元素包含匹配项The first element contains matching items
    • 第二个元素包含剩余项The second element contains the remaining items

下面的示例演示如何从数组中选择所有奇数。The following example shows how to select all odd numbers from the array.

(0..9).Where{ $_ % 2 }
1
3
5
7
9

此示例演示如何选择不为空的字符串。This example show how to select the strings that are not empty.

('hi', '', 'there').Where({$_.Length})
hi
there

默认Default

Default模式使用 scriptblock 筛选项 ExpressionThe Default mode filters items using the Expression scriptblock.

如果 numberToReturn 提供了,则它指定要返回的最大项数。If a numberToReturn is provided, it specifies the maximum number of items to return.

# Get the zip files in the current users profile, sorted by LastAccessTime.
$Zips = dir $env:userprofile -Recurse '*.zip' | Sort-Object LastAccessTime
# Get the least accessed file over 100MB
$Zips.Where({$_.Length -gt 100MB}, 'Default', 1)

备注

Default模式和模式都 First 返回第一个 (numberToReturn) 项,可以互换使用。Both the Default mode and First mode return the first (numberToReturn) items, and can be used interchangeably.

上一个Last

$h = (Get-Date).AddHours(-1)
$logs = dir 'C:\' -Recurse '*.log' | Sort-Object CreationTime
# Find the last 5 log files created in the past hour.
$logs.Where({$_.CreationTime -gt $h}, 'Last', 5)

跳到SkipUntil

SkipUntil模式将跳过集合中的所有对象,直到对象传递脚本块表达式筛选器。The SkipUntil mode skips all objects in a collection until an object passes the script block expression filter. 然后,它将返回 所有 剩余的集合项而不测试它们。It then returns ALL remaining collection items without testing them. 仅测试一个传递项Only one passing item is tested .

这意味着返回的集合包含未经过测试的 传递非传递 项。This means the returned collection contains both passing and non-passing items that have NOT been tested.

通过将值传递给参数,可以限制返回的项数 numberToReturnThe number of items returned can be limited by passing a value to the numberToReturn argument.

$computers = "Server01", "Server02", "Server03", "localhost", "Server04"
# Find the first available online server.
$computers.Where({ Test-Connection $_ }, 'SkipUntil', 1)
localhost

UntilUntil

Until模式反转 SkipUntil 模式。The Until mode inverts the SkipUntil mode. 它将返回集合中的 所有 项,直到某个项通过脚本块表达式。It returns ALL items in a collection until an item passes the script block expression. 在项 传递 scriptblock 表达式后,该 Where 方法将停止处理项。Once an item passes the scriptblock expression, the Where method stops processing items.

这意味着从方法接收第一组 非传递WhereThis means that you receive the first set of non-passing items from the Where method. 一项通过 ,就不会测试或返回其余的项。After one item passes, the rest are NOT tested or returned.

通过将值传递给参数,可以限制返回的项数 numberToReturnThe number of items returned can be limited by passing a value to the numberToReturn argument.

# Retrieve the first set of numbers less than or equal to 10.
(1..50).Where({$_ -gt 10}, 'Until')
# This would perform the same operation.
(1..50).Where({$_ -le 10})
1
2
3
4
5
6
7
8
9
10

备注

UntilSkipUntil 在不测试一批项目的前提下运行。Both Until and SkipUntil operate under the premise of NOT testing a batch of items.

Until返回第一个 阶段之前 的项。Until returns the items BEFORE the first pass .

SkipUntil返回第一次 传递 的所有项,包括第一次传递项。SkipUntil returns all the items AFTER the first pass , including the first passing item.

拆分Split

Split模式将集合项拆分为两个单独的集合。The Split mode splits, or groups collection items into two separate collections. 传递 scriptblock 表达式的和不是的那些表达式。Those that pass the scriptblock expression, and those that do not.

如果 numberToReturn 指定了,则第一个集合包含 传递 项,而不是超过指定的值。If a numberToReturn is specified, the first collection, contains the passing items, not to exceed the value specified.

其余的对象(甚至是那些 传递 表达式筛选器的对象)在第二个集合中返回。The remaining objects, even those that PASS the expression filter, are returned in the second collection.

$running, $stopped = (Get-Service).Where({$_.Status -eq 'Running'}, 'Split')
$running
Status   Name               DisplayName
------   ----               -----------
Running  Appinfo            Application Information
Running  AudioEndpointBu... Windows Audio Endpoint Builder
Running  Audiosrv           Windows Audio
...
$stopped
Status   Name               DisplayName
------   ----               -----------
Stopped  AJRouter           AllJoyn Router Service
Stopped  ALG                Application Layer Gateway Service
Stopped  AppIDSvc           Application Identity
...

获取数组的成员Get the members of an array

若要获取数组的属性和方法(如 Length 属性和 SetValue 方法),请使用 Cmdlet 的 InputObject 参数 Get-MemberTo get the properties and methods of an array, such as the Length property and the SetValue method, use the InputObject parameter of the Get-Member cmdlet.

将数组传递给时 Get-Member ,PowerShell 将一次发送一个项并 Get-Member 返回数组中每个项的类型 (忽略重复项) 。When you pipe an array to Get-Member, PowerShell sends the items one at a time and Get-Member returns the type of each item in the array (ignoring duplicates).

当使用 InputObject 参数时,将 Get-Member 返回数组的成员。When you use the InputObject parameter, Get-Member returns the members of the array.

例如,以下命令将获取 $a 数组变量的成员。For example, the following command gets the members of the $a array variable.

Get-Member -InputObject $a

还可以通过在将管道传递给 cmdlet 的值之前键入逗号 ) ( 来获取数组的成员 Get-MemberYou can also get the members of an array by typing a comma (,) before the value that is piped to the Get-Member cmdlet. 逗号使数组成为数组的数组中的第二项。The comma makes the array the second item in an array of arrays. PowerShell 将每次一个数组传递到数组,并 Get-Member 返回数组的成员。PowerShell pipes the arrays one at a time and Get-Member returns the members of the array. 类似于接下来的两个示例。Like the next two examples.

,$a | Get-Member

,(1,2,3) | Get-Member

操作数组Manipulating an array

您可以更改数组中的元素,将元素添加到数组,并将两个数组中的值合并为第三个数组。You can change the elements in an array, add an element to an array, and combine the values from two arrays into a third array.

若要更改数组中特定元素的值,请指定要更改的元素的数组名称和索引,然后使用赋值运算符 (=) 为该元素指定一个新值。To change the value of a particular element in an array, specify the array name and the index of the element that you want to change, and then use the assignment operator (=) to specify a new value for the element. 例如,若要更改数组中第二项的值 $a (索引位置 1) 为10,请键入:For example, to change the value of the second item in the $a array (index position 1) to 10, type:

$a[1] = 10

还可以使用数组的 SetValue 方法来更改值。You can also use the SetValue method of an array to change a value. 下面的示例将数组的第二个值 (索引位置 1) 更改 $a 为500:The following example changes the second value (index position 1) of the $a array to 500:

$a.SetValue(500,1)

可以使用 += 运算符将元素添加到数组中。You can use the += operator to add an element to an array. 下面的示例演示如何将元素添加到 $a 数组中。The following example shows how to add an element to the $a array.

$a = @(0..4)
$a += 5

备注

使用 += 运算符时,PowerShell 实际上会创建一个新数组,其中包含原始数组的值和所添加的值。When you use the += operator, PowerShell actually creates a new array with the values of the original array and the added value. 如果多次重复操作或数组大小太大,则这可能会导致性能问题。This might cause performance issues if the operation is repeated several times or the size of the array is too big.

从数组中删除元素并不容易,但你可以创建一个新的数组,其中仅包含现有数组的选定元素。It is not easy to delete elements from an array, but you can create a new array that contains only selected elements of an existing array. 例如,若要创建数组 $t ,其中包含 $a 数组中除索引位置2处的值之外的所有元素,请键入:For example, to create the $t array with all the elements in the $a array except for the value at index position 2, type:

$t = $a[0,1 + 3..($a.length - 1)]

若要将两个数组合并成单个数组,请使用加运算符 (+) 。To combine two arrays into a single array, use the plus operator (+). 下面的示例创建两个数组,并将它们组合在一起,然后显示生成的合并数组。The following example creates two arrays, combines them, and then displays the resulting combined array.

$x = 1,3
$y = 5,9
$z = $x + $y

因此,该 $z 数组包含1、3、5和9。As a result, the $z array contains 1, 3, 5, and 9.

若要删除数组,请将值分配 $null 给数组。To delete an array, assign a value of $null to the array. 以下命令删除变量中的数组 $aThe following command deletes the array in the $a variable.

$a = $null

你还可以使用 Remove-Item cmdlet,但赋予的值 $null 更快,尤其是对于大型数组。You can also use the Remove-Item cmdlet, but assigning a value of $null is faster, especially for large arrays.

零或一的数组Arrays of zero or one

从 Windows PowerShell 3.0 开始,零个或一个对象的集合具有 Count 和 Length 属性。Beginning in Windows PowerShell 3.0, a collection of zero or one object has the Count and Length property. 此外,还可以为一个对象的数组编制索引。Also, you can index into an array of one object. 此功能可帮助您避免在需要集合的命令获取的项少于两个项时出现脚本错误。This feature helps you to avoid scripting errors that occur when a command that expects a collection gets fewer than two items.

下面的示例演示了此功能。The following examples demonstrate this feature.

零个对象Zero objects

$a = $null
$a.Count
$a.Length
0
0

一个对象One object

$a = 4
$a.Count
$a.Length
$a[0]
$a[-1]
1
1
4
4

对 System.object 对象的索引支持Indexing support for System.Tuple objects

PowerShell 6.1 添加了对 元组 对象的索引访问的支持,类似于数组。PowerShell 6.1 added the support for indexed access of Tuple objects, similar to arrays. 例如:For example:

PS> $tuple = [Tuple]::Create(1, 'test')
PS> $tuple[0]
1
PS> $tuple[1]
test
PS> $tuple[0..1]
1
test
PS> $tuple[-1]
test

与数组和其他集合对象不同,当通过管道或支持对象数组的参数传递元组对象时,会将 元组 对象视为单个对象。Unlike arrays and other collection objects, Tuple objects are treated as a single object when passed through the pipeline or by parameters that support arrays of objects.

有关详细信息,请参阅 system.objectFor more information, see System.Tuple.

另请参阅See also