Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Microsoft Exchange Server 2016 PowerShell Cookbook

You're reading from   Microsoft Exchange Server 2016 PowerShell Cookbook Powerful recipes to automate time-consuming administrative tasks

Arrow left icon
Product type Paperback
Published in Jul 2017
Publisher
ISBN-13 9781787126930
Length 648 pages
Edition 4th Edition
Languages
Arrow right icon
Authors (4):
Arrow left icon
Mike Pfeiffer Mike Pfeiffer
Author Profile Icon Mike Pfeiffer
Mike Pfeiffer
Nuno Filipe M Mota Nuno Filipe M Mota
Author Profile Icon Nuno Filipe M Mota
Nuno Filipe M Mota
Nuno Mota Nuno Mota
Author Profile Icon Nuno Mota
Nuno Mota
Jonas Andersson Jonas Andersson
Author Profile Icon Jonas Andersson
Jonas Andersson
Arrow right icon
View More author details
Toc

Table of Contents (17) Chapters Close

Preface 1. PowerShell Key Concepts FREE CHAPTER 2. Exchange Management Shell Common Tasks 3. Managing Recipients 4. Managing Mailboxes 5. Distribution Groups and Address Lists 6. Mailbox Database Management 7. Managing Client Access 8. Managing Transport Servers 9. Exchange Security 10. Compliance and Audit Logging 11. High Availability 12. Monitoring Exchange Health 13. Integration 14. Scripting with the Exchange Web Services Managed API 15. Common Shell Information 16. Query Syntaxes

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 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 in 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, meaning 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 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 operators:

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

In this example, we are working with a one-dimensional array, which is what you'll commonly be 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've figured out how arrays work, let's take a closer look at hash tables. When viewing the output for a hash table, the items are returned in no particular order. You'll notice this when viewing 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 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 splitting. 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 example:

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 next:

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

    $mailboxes = @(Get-Mailbox testuser)  

You can see here that we've 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 multi-valued properties, just as we would with a normal array. To add an email 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 email 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  
There is actually an easier way to add and remove email addresses on recipient objects. See Adding and removing recipient email addresses recipe in Chapter 3 for details.

We've covered the core concepts in this section that you'll need to know when working with arrays. For more details, run Get-Help about_arrays.

See also

  • The Working with variables and objects recipe in this chapter
  • The Creating custom objects recipe in this chapter
You have been reading a chapter from
Microsoft Exchange Server 2016 PowerShell Cookbook - Fourth Edition
Published in: Jul 2017
Publisher:
ISBN-13: 9781787126930
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image