Book Image

Microsoft Exchange Server Powershell Cookbook (Update)

Book Image

Microsoft Exchange Server Powershell Cookbook (Update)

Overview of this book

Table of Contents (21 chapters)
Microsoft Exchange Server PowerShell Cookbook Third Edition
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Working with arrays and hash tables


Like many other scripting and programming languages, Windows PowerShell allows you to work with arrays and hash tables. An array is a collection of values that can be stored in a single object. A hash table is also known as an associative array and is a dictionary that stores a set of key-value pairs. You'll need to have a good grasp of arrays so that you can effectively manage objects in bulk and gain maximum efficiency in the shell. In this recipe, we'll take a look at how we can use both types of arrays to store and retrieve data.

How to do it...

You can initialize an array that stores a set of items by assigning multiple values to a variable. All you need to do is separate each value with a comma. The following command would create an array of server names:

$servers = "EX1","EX2","EX3"

To create an empty hash table, use the following syntax:

$hashtable = @{}

Now that we have an empty hash table, we can add key-value pairs:

$hashtable["server1"] = 1
$hashtable["server2"] = 2
$hashtable["server3"] = 3

Notice in this example that we can assign a value based on a key name, not by using an index number, as we saw with a regular array. Alternatively, we can create this same object using a single command, using the following syntax:

$hashtable = @{server1 = 1; server2 = 2; server3 = 3}

You can see here that we used a semicolon (;) to separate each key-value pair. This is only required if the entire hash table is created on one line.

You can break this up into multiple lines to make it easier to read:

$hashtable = @{
  server1 = 1
  server2 = 2
  server3 = 3
}

To create an empty array, use the following syntax:

$servers = @()

How it works...

Let's start off by looking at how arrays work in PowerShell. When working with arrays, you can access specific items and add or remove elements. In our first example, we assigned a list of server names to the $servers array. To view all of the items in the array, simply type the variable name and hit return:

[PS] C:\>$servers
EX1
EX2
EX3

Array indexing allows you to access a specific element of an array using its index number inside square brackets ([]). PowerShell arrays are zero-based, which means that the first item in the array starts at index zero. For example, use the second index to access the third element of the array, as shown next:

[PS] C:\>$servers[2]
EX3

To assign a value to a specific element of the array, use the equals (=) assignment operator. We can change the value from the last example using the following syntax:

[PS] C:\>$servers[2] = "EX4"
[PS] C:\>$servers[2]
EX4

Let's add another server to this array. To append a value, use the plus equals (+=) assignment operator, as shown here:

[PS] C:\>$servers += "EX5"
[PS] C:\>$servers
EX1
EX2
EX4
EX5

To determine how many items are in an array, we can access the Count property to retrieve the total number of array elements:

[PS] C:\>$servers.Count
4

We can loop through each element in the array with the ForEach-Object cmdlet and display the value in a string:

$servers | ForEach-Object {"Server Name: $_"}

We can also check for a value in an array using the -Contains or -NotContains conditional operator:

[PS] C:\>$servers -contains "EX1"
True

In this example, we are working with a one-dimensional array, which is what you'll be commonly dealing with in the Exchange Management Shell. PowerShell supports more complex array types, such as jagged and multidimensional arrays, but these are beyond the scope of what you'll need to know for the examples in this book.

Now that we have figured out how arrays work, let's take a closer look at hash tables. When we view the output for a hash table, the items are returned in no particular order. You'll notice this when we view the hash table we created earlier:

[PS] C:\>$hashtable
Name                         Value
----                         -----
server2                        2
server3                        3
server1                        1

If you want to sort the hash table, you can call the GetEnumerator method and sort by using the Value property:

[PS] C:\>$hashtable.GetEnumerator() | sort value
Name                         Value
----                         -----
server1                        1
server2                        2
server3                        3

Hash tables can be used when creating custom objects or to provide a set of parameter names and values using parameter splatting. Instead of specifying parameter names one by one with a cmdlet, you can use a hash table with keys that match the parameter's names and their associated values will automatically be used for input:

$parameters = @{
  Title = "Manager"
  Department = "Sales"
  Office = "Headquarters"
}
Set-User testuser @parameters

This command automatically populates the parameter values for Title, Department, and Office when running the Set-User cmdlet for the testuser mailbox.

For more details and examples for working with hash tables, run Get-Help about_Hash_Tables.

There's more…

You can think of a collection as an array created from the output of a command. For example, the Get-Mailbox cmdlet can be used to create an object that stores a collection of mailboxes, and we can work with this object just as we would with any other array. You'll notice that, when working with collections, such as a set of mailboxes, you can access each mailbox instance as an array element. Consider the following screenshot:

First, we retrieve a list of mailboxes that start with the letter t and assign that to the $mailboxes variable. From looking at the items in the $mailboxes object, we can see that the testuser mailbox is the second mailbox in the collection.

Since arrays are zero-based, we can access that item using the first index, as shown in the following screenshot:

In previous version(s) of the Exchange Server, we had an issue when the command only returned one item; the output could not be accessed using the array notation. If you face this, it can be solved using the following syntax:

$mailboxes = @(Get-Mailbox testuser)

You can see here that we wrapped the command inside the @() characters to ensure that PowerShell will always interpret the $mailboxes object as an array. This can be useful when you're building a script that always needs to work with an object as an array, regardless of the number of items returned from the command that created the object. Since the $mailboxes object has been initialized as an array, you can add and remove elements as needed.

We can also add and remove items to multivalued properties, just as we would with a normal array. To add an e-mail address to the testuser mailbox, we can use the following commands:

$mailbox = Get-Mailbox testuser
$mailbox.EmailAddresses += "[email protected]"
Set-Mailbox testuser -EmailAddresses $mailbox.EmailAddresses

In this example, we created an instance of the testuser mailbox by assigning the command to the $mailbox object. We can then work with the EmailAddresses property to view, add, and remove e-mail addresses from this mailbox. You can see here that the plus equals (+=) operator was used to append a value to the EmailAddresses property.

We can also remove that value using the minus equals (-=) operator:

$mailbox.EmailAddresses -= "[email protected]"
Set-Mailbox testuser -EmailAddresses $mailbox.EmailAddresses

Tip

There is actually an easier way to add and remove e-mail addresses on recipient objects. See Adding and removing recipient e-mail addresses in Chapter 3, Managing Recipients, for details.

In this section, we covered the core concepts that you'll need to know while working with arrays. For more details, run Get-Help about_arrays.

See also

  • Working with variables and objects

  • Creating custom objects