Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
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

Looping through items

Loop processing is a concept that you will need to master in order to write scripts and one-liners with efficiency. You'll need to use loops to iterate over each item in an array or a collection of items, and then run one or more commands within a script block against each of those objects. In this recipe, we'll take a look at how you can use foreach loops and the ForEach-Object cmdlet to process items in a collection.

How to do it...

The foreach statement is a language construct used to iterate through values in a collection of items. The following example shows the syntax used to loop through a collection of mailboxes, returning only the name of each mailbox:

    foreach ($mailbox in Get-Mailbox) {$mailbox.Name}  

In addition, you can take advantage of the PowerShell pipeline and perform loop processing using the ForEach-Object cmdlet. This example produces the same result as the one shown previously:

    Get-Mailbox | ForEach-Object {$_.Name}  

You will often see the given command written using an alias of the ForEach-Object cmdlet, such as the percent sign (%):

    Get-Mailbox | %{$_.Name}  

How it works...

The first part of a foreach statement is enclosed in parentheses and represents a variable and a collection. In the previous example, the collection is the list of mailboxes returned from the Get-Mailbox cmdlet. The script block contains the commands that will be run for every item in the collection of mailboxes. Inside the script block, the $mailbox object is assigned the value of the current item being processed in the loop. This allows you to access each mailbox one at a time using the $mailbox variable.

When you need to perform loop processing within a pipeline, you can use the ForEach-Object cmdlet. The concept is similar, but the syntax is different because objects in the collection are coming across the pipeline.

The ForEach-Object cmdlet allows you to process each item in a collection using the $_ automatic variable, which represents the current object in the pipeline. The ForEach-Object cmdlet is probably one of the most commonly-used cmdlets in PowerShell, and we'll rely on it heavily in many examples throughout the book.

The code inside the script block used with both looping methods can be more complex than just a simple expression. The script block can contain a series of commands or an entire script. Consider the following code:

Get-MailboxDatabase -Status | %{ 
  $DBName = $_.Name 
  $whiteSpace = $_.AvailableNewMailboxSpace.ToMb() 
  "The $DBName database has $whiteSpace MB of total white space" 
} 

In this example, we're looping through each mailbox database in the organization using the ForEach-Object cmdlet. Inside the script block, we've created multiple variables, calculated the total megabytes of whitespace in each database, and returned a custom message that includes the database name and corresponding whitespace value. This is a simple example, but keep in mind that inside the script block, you can run other cmdlets, work with variables, create custom objects, and more.

PowerShell also supports other language constructs for processing items such as for, while, and do loops. Although these can be useful in some cases, in the next recipe we will use while and do loops as examples. You can read more about them and view examples using the get-helpabout_for, get-helpabout_while, and get-help about_do commands in the shell.

There's more...

There are some key differences about the foreach statement and the ForEach-Object cmdlet that you'll want to be aware of when you need to work with loops. First, the ForEach-Object cmdlet can process one object at a time as it comes across the pipeline. When you process a collection using the foreach statement, this is the exact opposite. The foreach statement requires that all of the objects that need to be processed within a loop are collected and stored in memory before processing begins. We'll want to take advantage of the PowerShell pipeline and its streaming behavior whenever possible since it is much more efficient.

The other thing to make note of is that in PowerShell, foreach is not only a keyword, but also an alias. This can be a little counterintuitive, especially when you are new to PowerShell and you run into a code sample that uses the following syntax:

    Get-Mailbox | foreach {$_.Name}  

At first glance, this might seem like we're using the foreach keyword, but we're actually using an alias for the ForEach-Object cmdlet. The easiest way to remember this distinction is that the foreach language construct is always used before a pipeline. If you use foreach after a pipeline, PowerShell will use the foreach alias which corresponds to the ForEach-Object cmdlet.

Another common loop is the for loop; its ideal where the same sequence of statements need to be repeated a specific number of times. Explaining the for loop is probably most easily done by illustrating an example:

for (initialize; condition; increment) { 
code block 
} 

Initialize section - You set a variable with a starting value. In the initialize segment, you can set one or more variables by separating them with commas.

Condition section - The condition is tested each time by PowerShell before it executes the code. If the condition is found to be true, your body of code will be executed. If the condition is found to be false, PowerShell stops executing the code.

Increment section - In this section, you specify how you want the variable to be updated after each run of the loop. This can be an increment or a decrement or any other change you need. After the code has been executed once, PowerShell will update your variable.

The for loop keeps on looping until your conditional turns false, just like the following example:

for ($i = 1; $i -le 10; $i++) { 
Write-Host $i 
} 

In this example, initially $i is set to a value of 1. The loop will run until $i is less or equal to 10. Our example will write the value for $i on the screen.

Another common loop is the do while and while loop, this loop executes until the condition value is True. This kind of loop can be helpful when moving mailboxes. The loop can then be used for verifying that the move is proceeding as expected and has finished successfully. In that case, the move status would be the condition that the loop is using:

do { code block }
while (condition)

The two different sections are shown in the preceding code and they are almost self-explanatory. Under the do section, the code is written; as our following example shows, we are using Write-Host.

Under the while section, the condition is set; in our example, the condition is that $i is less 10:

$i = 1
do { Write-Host $i
$i++
}
while ($i -le 10)

See also

  • The Working with arrays and hash tables recipe in this chapter
  • The Understanding the pipeline 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