Collection β
Array Creation β
From Constructor β
$bar = [int[]]::new(5)From Comma Operator β
Commas , create an array literal.
$array = 1,2,3
$single = ,1 # array with only one item2
From Array SubExpression Operator β
@() allows to spread collections to be part of a new array, expressions are separated by ;
@(<expr1>[; <expr2>...])
$foo = @(1,2,3) # convoluted, @() unpacks inner array literal
$foo = @() # empty array2
3
4
5
IMPORTANT
; distinguishes expressions while , creates array by the context
Array Merging β
Given the nature of @() we can use it to merge different sources of collection-like objects/statement
@(1,2,3; 1,2,3).Length # 6
@(gci).Lengeth # 11
@(gci; gci).Lengeth # 22
@(@(1,2,3); @(1,2,3)).Length # 6
# merge from collections
$list = [System.Collections.Generic.List[string]]@(1,2,3)
@($foo; @(1,2,3)).Length # 6
# merge from enumerator
$table = @{ foo = 123; bar = 123 }
@($table.GetEnumerator(); @(1,2,3)).Length # 5
# merge from control flow
@(
if ($true) {
'yield this value to the array'
'yield this value again'
};
@(1,2,3)
).Length # 52
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
From Range β
Range operator can create array from integer range and character range inclusively from both sides.
NOTE
character range was added in PowerShell 6
1..10 # 1 to 10 inclusively
'a'..'z' # a to z inclusively2
If the end is less than the start, the array counts down from start to end
5..1 # 5 4 3 2 1
5..-1 # 5 4 3 2 1 0 -12
Item Accessor β
Powershell allows indexer syntax to access one or more items at a time or use Select-Object.
@(1,2,3)[0] # 1
@(1,2,3) | select -index 1 # 2
@(1,2,3)[0, 1] # 1, 2 returns an array though2
3
NOTE
The default value of a array item is $null. Since it's a dynamic language, there's no error raised when index is out of the range.
Singular as Collection β
Variables storing singular value are intrinsically collections in PowerShell, so you don't have to check on the length when an return might be singular or a collection. Value at index 0 is the value stored by variable itself, otherwise it returns $null.
$foo = 1
$foo[0] # 1
$foo[1] # $null
if (Get-Command foo -OutVariable exe) {
# Get-Command might return one or more instances,
# but we don't need to check on length.
# everything is an collection!
& $exe[0]
}2
3
4
5
6
7
8
9
10
Concatenation β
Generates new array from two concatenated or with new item.
((1,2,3) + (1,2,3)).Length # 6
(1,2,3) + 4 # 1,2,3,42
NOTE
Can use += when you operate on a array variable.
Repetition β
Use * to repeat the array content for certain times.
((1,2,3) * 3).Length # 9A practical usage of repetition is initialization with same value to the whole array.
@(255) * 100 # Fill up array sized 100 with 255 to all elementsSlicing β
Use range operator to slice an array.
(1..10)[0..5] # 1 to 6
(1..10)[-3..-1] # 8 to 10, last 3 items
# Reversed slicing
(1..10)[-1..-3] # 10, 9, 8; last 3 items in a reversed order
((1..10)[-1..-1]) -is [Array] # True, slicing always returns array2
3
4
5
6
7
8
NOTE
Differ from C#, range operator in Powershell is inclusive from both sides.
Range Unions β
You can specify multiple ranges for slicing with +, selected item will be collected together. Separate different ranges by + to generate a range union.
NOTE
A range can be a single index or simple range
# Select 1 to 3, 5 to 6, and a single 8
(1..10)[0..2+4..5+7]2
Subtraction β
To subtract a collection from another collection, you can certainly use LINQ or use a simple pipeline.
@(1,2,3) | where { @(1, 2) -notcontains $_ } # 3Equality Checking β
Collections behave differently in Powershell on equality checking, they're not based on reference but the contained items.
<arr> -eq <item>: returns all items in<arr>equal to<item>.<arr> -ne <item>: returns all items in<arr>not equal to<item>.- always returns
object[]even for single result or no result.
1,1,2,3 -eq 1 # 1,1
'a','b','c' -ne 'a' # 'b', 'c'
# the whole item is an array so no result is returned.
1,1,2,3 -eq 1,2 # empty array2
3
4
5
TIP
You can use -ne to exclude single item from a collection.
NOTE
To do reference checking, use [object]::ReferenceEquals.
Null Checking β
Checking null for collections is a quirk in PowerShell, $arr -eq $null checks all items instead of the whole array.
$arr = 1,2,3
$arr -eq $null # empty array
$null -eq $arr # False, the result we expected #2
3
4
5
TIP
Always leave array as the right operand on null checking.
To List β
PowerShell allows direct casting a array to an ArrayList or generic List<T>.
using namespace System.Collections.Generic
[List[int]]@(1,2,3)
[System.Collections.ArrayList]@(1,2,3)2
3
4
5
Filtering & Transformation by Keyword Operators β
Keyword operators has special functionalities on collections. -match, -notmatch, -replace, -split handles for all items in the left operand collection, the result is always an array.
# Returns items that matches the regex
@('John', 'Jane', 'Janet') -match 'Jane' # Jane, Janet.
(gci -file) -match '.*txt$' # FileInfo with FullName matches to the pattern
(@('John', 'Jane', 'Janet') -notmatch 'Jane') -is [Array] # True, only John matches and still an array.
@('John', 'Jane', 'Janet') -replace 'J','K' # Kohn Kane Kanet
'1,2,3','1,2,3' -split ',' # 1 2 3 1 2 3, strings2
3
4
5
6
7
NOTE
If current item for -match or -notmatch is not a string, Powershell evaluates it to string by certain strategy.
TIP
Match and replace is case-insensitive by default. Use -cmatch, -cnotmatch, -creplace, -csplit for case-sensitive scenarios.
Deconstruction β
$a, $b, $c = 1,2,3 # $a = 1, $b = 2, $c = 3
$a, $b = 1,2,3 # $a = 1, $b = 3 This might not be expected #2
WARNING
You should only use deconstruction when you need the first and the last item returned or you're pretty sure there's only two element will be returned.
Multi-Dim Array β
You'll have to create Multi-Dim array from .NET type constructor only.
$foo = [int[,]]::New(2, 2) # 2 * 2 array