Working with Arrays

If you want to put a couple of numbers or some strings into an array you can do this:
$a1 = 1,2,3,4
$a2= "Bill", "Fred", "John"

You can then use the following to test how many items are in each array:

PowerShell is flexible enough to allow text and numbers in the same array, as it sees both as just objects. You can join arrays as follows:
$a = $a1 + $a2
$b = $a1, $a2

However, watch out, the first method with a plus sign does indeed take all the elements of both arrays and merge them into one big array, however the comma makes an array with two items in, the two arrays, in other words, an array of arrays, possibly not what you wanted or expected! You can prove this with the length method.

Sorting Arrays

When sorting arrays you might have an array of objects, in which case you might want to sort by a specific property, the following example shows how to do this:
$events = $events | Sort-Object -Property TimeCreated -Descending

A quirk of PowerShell

I have recently noticed that some Cmdlets can return both single objects or arrays of objects but if you don't expect this you can have un-intended consequences! For example Get-ChildItem for FileSystem can return an array or just a single item. If you store the output in a variable then the Length method might return the number of elements in the array or the size of the file, potentially a big difference and confusing. However it is worth noting that ForEach-Object works fine with an array or single object, which is very useful. The sections on "Testing for Arrays" and "Forcing an Array" will also help.

Testing for Arrays

There are times when you need to test if what you have is an array. Here is an example of testing if something is an array:
if ($Files -is [array]) {
    Write-Host "We have an array"
} else {
    Write-Host "It is not an array"

Forcing an Array

If you are getting information from a Cmdlet or Function you can use "@()" to make sure it is an array, irrespective of how many items are actually returned. For example:
@(Get-ChildItem -Path "." -File -Filter "*.txt")
is now guaranteed to be an array, irrespective of how many files are found.

Extra Information

For more information on working with arrays see Learn Simple Ways to Handle Windows PowerShell Arrays - Hey, Scripting Guy! Blog - TechNet Blogs and Add, Modify, Verify, and Sort Your PowerShell Array - Hey, Scripting Guy! Blog - TechNet Blogs