PowerShell by Myles

PowerShell Array Guide

Arrays are a fundamental feature of PowerShell. Arrays make it possible to ingest, manipulate and output true data structures (and not just raw strings). This capability makes PowerShell different and more useful than other scripting languages.

...see more

In real-time application requirements, we will work with a custom PowerShell object array (complex object) instead of a simple string or integer array. The Unique switched parameter can also be used to find distinct objects by a property in a custom object array.

# Initialize the array
$Array = @()
 
$Array += [PSCustomObject]@{ Name = "User1"; }
$Array += [PSCustomObject]@{ Name = "User2"; }
$Array += [PSCustomObject]@{ Name = "User2"; }
$Array += [PSCustomObject]@{ Name = "User3"; }
 
$ResultArray = $Array | Select-Object -Unique -Property Name
  
$ResultArray # Result array with unique Name values
  
Name
----
User1
User2
User3

As already explained, the Unique parameter with Select-Object cmdlet finds unique values with case-sensitive string comparison. If you work with a string property and want to perform a case-insensitive string comparison to find distinct objects, then we need to use the Unique parameter with Sort-Object cmdlet to perform a case-insensitive check.

# Initialize the array
$Array = @()
 
$Array += [PSCustomObject]@{ Name = "User1"; }
$Array += [PSCustomObject]@{ Name = "user2"; }
$Array += [PSCustomObject]@{ Name = "User2"; }
$Array += [PSCustomObject]@{ Name = "User3"; }
 
# Find unique objects by case-sensitive comparison.
$Array | Select-Object -Unique -Property Name
  
Name
----
User1
user2
User2
User3 
  
# Find unique objects by case-insensitive comparison.
$Array | Sort-Object -Unique -Property Name 
  
Name
----
User1
User2
User3
...see more

There are three methods to create and define an array. Based on these three methods, below are the three syntaxes of a PowerShell array:

In the first syntax, an array is created by enclosing the items in the @() parentheses.

$ArrayList = @('item 1', 'item 2', 'item 3')

The second syntax creates an array with items in a comma-separated list.

$ArrayList  = 'item 1', 'item 2', 'item 3'

The third syntax creates an array with a specific data type.

[ArrayType[]]$ArrayList = 'item 1', 'item 2', 'item 3'
...see more

To access an item in an array we can use an index.

$ArrayList = @('item 1', 'item 2', 'item 3')
$ArrayList [1]
item 2

Comments