## 创建和初始化数组

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

``````\$B = ,7
``````

``````\$C = 5..8
``````

``````\$A.GetType()
``````

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

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

## 数组子表达式运算符

``````@( ... )
``````

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

``````\$p = @(Get-Process Notepad)
``````

## 访问和使用数组元素

### 读取数组

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

``````\$a[0]
``````
``````0
``````

``````\$a[2]
``````
``````2
``````

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

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

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

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

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

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

### 对数组元素的迭代

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

`For` 检查数组中的元素时，循环在递增计数器时非常有用。 例如，若要使用 `For` 循环返回数组中的每个其他值，请键入：

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

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

## 数组的属性

### Count 或 Length 或 LongLength

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

### Rank

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

"`\$a rank: \$(\$a.Rank)"
"`\$a length: \$(\$a.Length)"
"`\$a[2] length: \$(\$a[2].Length)"
"Process `\$a[2][1]: \$(\$a[2][1].ProcessName)"
``````

``````\$a rank: 1
\$a length: 3
\$a[2] length: 348
Process \$a[2][1]: AcroRd32
``````

``````[string[,]]\$rank2 = [string[,]]::New(3,2)
\$rank2.rank
\$rank2.Length
\$rank2[0,0] = 'a'
\$rank2[0,1] = 'b'
\$rank2[1,0] = 'c'
\$rank2[1,1] = 'd'
\$rank2[2,0] = 'e'
\$rank2[2,1] = 'f'
\$rank2[1,1]
``````
``````2
6
d
``````

``````\$a = "red",\$true
\$b = (New-Object 'int[,]' 2,2)
\$b[0,0] = 10
\$b[0,1] = 20
\$b[1,0] = 30
\$b[1,1] = 40
\$c = \$a + \$b
\$a.GetType().Name
\$b.GetType().Name
\$c.GetType().Name
\$c
``````

``````Object[]
Int32[,]
Object[]
red
True
10
20
30
40
``````

## 数组的方法

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

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

### ForEach

``````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 表达式、object[] 参数)

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

#### ForEach (类型 convertToType)

``````("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， object[] newValue)

``````# 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 (string methodName， object[] 参数)

Lastly， `ForEach` 方法可用于对集合中的每个项执行方法。

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

### 位置

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

• Default (0) - 返回所有项
• First (1) - 返回第一个项目
• Last (2) - 返回最后一个项目
• SkipUntil (3) - 跳过项，直到条件为 true，返回所有剩余项 (包括条件为 true 的第一个项目)
• Until (4) - 返回所有项，直到条件为 true
• Split (5) - 返回两个元素的数组
• 第一个元素包含匹配项
• 第二个元素包含剩余的项

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

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

#### Default

``````# 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` 项，并且可以互换使用。

#### 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

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

#### Until

``````# 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
``````

`SkipUntil`同时`Until`在 NOT 测试一批项目的前提下运行。

`Until`返回第一次传递的项。

`SkipUntil` 返回第一次传递 的所有项，包括第一个 传递项。

#### Split

``````\$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-Member -InputObject \$a
``````

``````,\$a | Get-Member

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

## 操作数组

``````\$a[1] = 10
``````

``````\$a.SetValue(500,1)
``````

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

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

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

`\$a = \$null`

## 零或一个数组

### 零对象

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

### 一个对象

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

## 对 System 的索引支持。Tuple 对象

PowerShell 6.1 添加了对对象进行索引访问 Tuple 的支持，类似于数组。 例如：

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

## 为实现的 .NET 类型编制索引 `IDictionary<TKey, TValue>`

``````PS> [Collections.Generic.Dictionary[string, int]]::new()['nosuchkey']
# No output (\$null)

PS> [Collections.Generic.Dictionary[string, int]]::new().Item('nosuchkey')
GetValueInvocationException: Exception getting "Item": "The given key 'nosuchkey' was not present in the dictionary."
``````

## 成员访问枚举

### 示例

``````\$files = (New-Item -Type File -Force '/temp/t1.txt'),
(New-Item -Force -Type File '/temp/t2.txt')
\$files.LastWriteTime
``````
``````Friday, June 25, 2021 1:21:17 PM
Friday, June 25, 2021 1:21:17 PM
``````

``````\$files.LastWriteTime = (Get-Date).AddDays(-1)
``````
``````InvalidOperation: The property 'LastWriteTime' cannot be found on this object.
Verify that the property exists and can be set.
``````

``````\$files.set_LastWriteTime((Get-Date).AddDays(-1))
\$files.LastWriteTime
``````
``````Thursday, June 24, 2021 1:23:30 PM
Thursday, June 24, 2021 1:23:30 PM
``````

``````\$files | Get-Member | Where-Object Definition -like '*set;*'
``````
``````   TypeName: System.IO.FileInfo

Name              MemberType Definition
----              ---------- ----------
Attributes        Property   System.IO.FileAttributes Attributes {get;set;}
CreationTime      Property   datetime CreationTime {get;set;}
CreationTimeUtc   Property   datetime CreationTimeUtc {get;set;}