Microsoft Exchange Server PowerShell Cookbook (2024)

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:

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:\>$serversEX1EX2EX3

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:\>$serversEX1EX2EX4EX5

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.Count4

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:\>$hashtableName Value---- -----server2 2server3 3server1 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 valueName Value---- -----server1 1server2 2server3 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:

Microsoft Exchange Server PowerShell Cookbook (1)

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:

Microsoft Exchange Server PowerShell Cookbook (2)

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 += "[emailprotected]"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 -= "[emailprotected]"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

Microsoft Exchange Server PowerShell Cookbook (2024)

FAQs

How to download exchange PowerShell module? ›

How to Install Exchange Online PowerShell Module
  1. Step 1: Set Windows PowerShell Execution Policy. ...
  2. Step 2: Set Up PowerShellGet Module. ...
  3. Step 3: Install the Exchange Online Management module. ...
  4. Step 4: Connect to Exchange Online PowerShell V3. ...
  5. Step 5: Use Commands Available in the Exchange Online Environment.
Dec 6, 2023

What is an exchange module? ›

The Exchange module is mainly used for: Repetitive data replication for multisite environment. Repetitive data replication for linking LN software to other software applications. Data conversions from one version of LN to another.

Is the exchange management shell the same as PowerShell? ›

The Exchange Management Shell is built on Windows PowerShell technology and provides a powerful command-line interface that enables the automation of Exchange administration tasks. You can use the Exchange Management Shell to manage every aspect of Exchange.

What is Microsoft Exchange Online PowerShell module? ›

The Exchange Online PowerShell module uses modern authentication and works with or without multi-factor authentication (MFA) for connecting to all Exchange-related PowerShell environments in Microsoft 365: Exchange Online PowerShell, Security & Compliance PowerShell, and standalone Exchange Online Protection (EOP) ...

How do I manually download PowerShell modules? ›

Download a module
  1. Navigate to the PowerShell Gallery1. Search for the desired module.
  2. Select the Manual Download tab.
  3. Click the Download the raw nupkg file.
  4. After the file finishes downloading, transfer it to the desired computer.
Dec 11, 2020

How do I get to Exchange Server PowerShell? ›

Here's how:
  1. Open PowerShell on your computer.
  2. Type “Get-ExchangeServer” and press Enter.
  3. You'll get a list of all the Exchange Servers in your environment.
  4. To narrow down the results, use “-Identity” or “-Status”.
  5. After you've identified the Exchange Server, take necessary actions.

Where are PowerShell modules stored? ›

These modules are stored in the $PSHOME\Modules folder. On Windows, modules installed in the AllUsers scope are stored in $env:ProgramFiles\WindowsPowerShell\Modules . On non-Windows systems, modules installed in the AllUsers scope are stored in /usr/local/share/powershell/Modules .

How to check if exchange online PowerShell module is installed? ›

The Get-InstalledModule cmdlet gets PowerShell modules that are installed on a computer using PowerShellGet. To see all modules installed on the system, use the Get-Module -ListAvailable command.

How to install a module in PowerShell? ›

From Gallery Recap
  1. Navigate to the PowerShell Gallery online to find modules or scripts to download.
  2. Identify the package you're interested in and examine the metadata on its specific page on the Gallery. ...
  3. Install the module or package using the 'Install-Module' or 'Install-Script' cmdlet.
Jan 9, 2024

How do I run an Exchange script in PowerShell? ›

Connecting to Exchange Online using Powershell
  1. First, you must ensure that you can run Powershell scripts without restrictions. ...
  2. Make sure that the “Administrator: Windows PowerShell” appears in the title bar. ...
  3. Click 'Yes'
  4. Afterwards, copy and paste the text below: ...
  5. Type 'Y'
  6. Copy and paste the text below:

What is the PowerShell command to start all Exchange services? ›

To do this, run the following PowerShell command: Get-Service -DisplayName "Microsoft Exchange*" | Where-Object {$_. Starttype -eq "Automatic" -and $_. Status -ne "Running"} | Start-Service​​​​​​​

What is the difference between shell and PowerShell? ›

PowerShell isn't just a shell; it's a complete scripting environment. PowerShell invokes lightweight commands called cmdlets at runtime. In addition, PowerShell is able to use external components such as the Windows Management Instrumentation (WMI) and the . NET Framework.

What is the latest version of Exchange PowerShell? ›

Version 3.2. 0 has been released. Virtually all Security & Compliance PowerShell cmdlets are now backed by the REST API, and REST API is used by default.

How to get mailbox details in PowerShell? ›

How to Use Get-MailboxFolderStatistics in PowerShell
  1. Step 1: Connect to Exchange Online PowerShell. To run cmdlets, we first need to connect to the Exchange Online PowerShell environment managed by your organization. ...
  2. Step 2: Identify the User Mailbox. ...
  3. Step 3: Run Get-MailboxFolderStatistics Cmdlet.
Jan 19, 2024

How to update a PowerShell module? ›

The Update-Module cmdlet installs a module's newest version from an online gallery. You're prompted to confirm the update before it's installed. Updates are installed only for modules that were installed on the local computer with Install-Module . Update-Module searches $env:PSModulePath for installed modules.

How do I download Exchange Module? ›

Exchange Online PowerShell module
  1. Download from PowerShell gallery.
  2. Run the module from Windows PowerShell and Windows PowerShell ISE.
  3. Single cmdlet Connect-ExchangeOnline supports both MFA and non-MFA accounts.
  4. EXO V3 cmdlets are REST API-based which are much faster and more reliable.
  5. EXO V3 uses Modern Authentication.
Dec 12, 2023

How to install Exchange PowerShell module offline? ›

To install a PowerShell module offline, you need to download the module from the PowerShell Gallery using an internet-connected computer, transfer the files to the offline machine using a secure method, and then use 'Import-Module' to install it on the target computer.

How to import o365 module in PowerShell? ›

Step 1: Install the MSOnline PowerShell Module
  1. powershell. ...
  2. Import-Module MSOnline.
  3. Get-Module MSOnline. ...
  4. (Get-Module MSOnline | Select-Object ExportedCommands). ...
  5. Change UserName@DomainName.com to your Office 365 user name. ...
  6. $ImpCred = Import-Clixml D:\PowerShellCred\Office365. ...
  7. Connect-MsolService -Credential $ImpCred.
Mar 15, 2023

Top Articles
Latest Posts
Article information

Author: Terrell Hackett

Last Updated:

Views: 6623

Rating: 4.1 / 5 (72 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Terrell Hackett

Birthday: 1992-03-17

Address: Suite 453 459 Gibson Squares, East Adriane, AK 71925-5692

Phone: +21811810803470

Job: Chief Representative

Hobby: Board games, Rock climbing, Ghost hunting, Origami, Kabaddi, Mushroom hunting, Gaming

Introduction: My name is Terrell Hackett, I am a gleaming, brainy, courageous, helpful, healthy, cooperative, graceful person who loves writing and wants to share my knowledge and understanding with you.