🎓 A1Learner
🔍
0 of 52 lessons completed

PowerShell Array Methods

Array methods are operations that work on a whole array at once. They sort it, test it, join it, or grow it.

Join an array into one line

Arrays print one value per line on their own. Join puts them on one line with a separator.

$fruits = @("apple", "banana", "cherry")
$fruits -join ", "
$fruits.Count

Sort an array and drop repeats

Sort-Object puts values in order. The Unique option drops repeated values.

$nums = @(3, 1, 2, 1)
$nums | Sort-Object -Unique

Test and grow an array

The contains operator answers true or false. Adding with += puts a new value at the end.

$colors = @("red", "green")
$colors -contains "green"
$colors += "purple"
$colors -join ", "

Example

$scores = @(70, 90, 80)
$scores += 100
$sorted = $scores | Sort-Object -Descending
$sorted -join ", "
$sorted.Count
$sorted -contains 90

Key points

  • Join: an operator that turns an array into one line of text with a separator between values.
  • Sort: an operation that puts array values in order, smallest first unless asked otherwise.
  • Unique: an option that drops repeated values while sorting.
  • Contains: an operator that tests whether an array holds a given value.
  • Grow an array by adding a value with +=.

In this example, a new score is added to the array first. The scores are then sorted from largest to smallest and saved in a new variable. The sorted scores print on one line, then the count prints, then the test for 90 prints.

Note

sorting with the pipeline leaves the original array unchanged unless you save the result.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does (@(3, 1, 2) | Sort-Object) -join ", " print?