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
Conferences
Free Learning
Arrow right icon
Microsoft Exchange Server 2013 PowerShell Cookbook: Second Edition
Microsoft Exchange Server 2013 PowerShell Cookbook: Second Edition

Microsoft Exchange Server 2013 PowerShell Cookbook: Second Edition: Benefit from over 120 recipes that tackle the everyday issues that arise with Microsoft Exchange Server. Using PowerShell you'll learn to add scripts that provide new functions and efficiencies. Only basic knowledge required. , Second Edition

eBook
€8.99 €39.99
Paperback
€48.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Microsoft Exchange Server 2013 PowerShell Cookbook: Second Edition

Chapter 1. PowerShell Key Concepts

In this chapter, we will cover the following:

  • Using the help system

  • Understanding command syntax and parameters

  • Understanding the pipeline

  • Working with variables and objects

  • Formatting output

  • Working with arrays and hash tables

  • Looping through items

  • Creating and running scripts

  • Using flow control statements

  • Creating custom objects

  • Creating PowerShell functions

  • Setting up a profile

Introduction


So, your organization has decided to move to Exchange Server 2013 to take advantage of the many exciting new features such as integrated e-mail archiving, discovery capabilities, and high availability functionality. Like it or not, you've realized that PowerShell is now an integral part of Exchange Server management and you need to learn the basics to have a point of reference for building your own scripts. That's what this book is all about. In this chapter, we'll cover some core PowerShell concepts that will provide you with a foundation of knowledge for using the remaining examples in this book. If you are already familiar with PowerShell, you may want to use this chapter as a review or as a reference for later on after you've started writing scripts.

If you're completely new to PowerShell, its concept may be familiar if you've worked with Unix command shells. Like Unix-based shells, PowerShell allows you to string multiple commands together on one line using a technique called pipelining. This means that the output of one command becomes the input for another. But, unlike Unix shells that pass text output from one command to another, PowerShell uses an object model based on the .NET Framework, and objects are passed between commands in a pipeline, as opposed to plain text. From an Exchange perspective, working with objects gives us the ability to access very detailed information about servers, mailboxes, databases, and more. For example, every mailbox you manage within the shell is an object with multiple properties, such as an e-mail address, database location, or send and receive limits. The ability to access this type of information through simple commands means that we can build powerful scripts that generate reports, make configuration changes, and perform maintenance tasks with ease.

Performing some basic steps

To work with the code samples in this chapter, follow these steps to launch the Exchange Management Shell:

  1. Log on to a workstation or server with the Exchange Management Tools installed.

  2. You can connect using remote PowerShell if you for some reason don't have Exchange Management Tools installed. Use the following command:

    $Session = New-PSSession -ConfigurationName Microsoft.Exchange `
    -ConnectionUri http://tlex01/PowerShell/ `
    -Authentication Kerberos `
    Import-PSSession $Session 
    
  3. Open the Exchange Management Shell by clicking on Start | All Programs | Microsoft Exchange Server 2013. Or if you're using Windows 2012 Server, it can be found by pressing the Windows key.

  4. Click on the Exchange Management Shell shortcut.

Note

Remember to start the Exchange Management Shell using Run As Admin to avoid permission problems.

In the chapter, notice that in the examples of cmdlets, I have used the back tick (`) character for breaking up long commands into multiple lines. The purpose with this is to make it easier to read. The back ticks are not required and should only be used if needed.

Using the help system


The Exchange Management Shell includes over 750 cmdlets (pronounced command-lets), each with a set of multiple parameters. For instance, the New-Mailbox cmdlet accepts more than 60 parameters, and the Set-Mailbox cmdlet has over 160 available parameters. It's safe to say that even the most experienced PowerShell expert would be at a disadvantage without a good help system. In this recipe, we'll take a look at how to get help in the Exchange Management Shell.

How to do it...

To get help information for a cmdlet, type Get-Help, followed by the cmdlet name. For example, to get help information about the Get-Mailbox cmdlet, run the following command:

Get-Help Get-Mailbox -full

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

How it works...

When running Get-Help for a cmdlet, a synopsis and description for the cmdlet will be displayed in the shell. The Get-Help cmdlet is one of the best discovery tools to use in PowerShell. You can use it when you're not quite sure how a cmdlet works or what parameters it provides.

You can use the following switch parameters to get specific information using the Get-Help cmdlet:

  • Detailed: The detailed view provides parameter descriptions and examples, and uses the following syntax:

    Get-Help<cmdletname>-Detailed
    
  • Examples: You can view multiple examples of how to use a cmdlet by running the following syntax:

    Get-Help<cmdletname>-Examples
    
  • Full: Use the following syntax to view the complete contents of the help file for a cmdlet:

    Get-Help<cmdletname>-Full
    

Some parameters accept simple strings as input, while others require an actual object. When creating a mailbox using the New-Mailbox cmdlet, you'll need to provide a secure string object for the -Password parameter. You can determine the data type required for a parameter using Get-Help:

You can see from the command output that we get several pieces of key information about the -Password parameter. In addition to the required data type of <SecureString>, we can see that this is a named parameter. It is required when running the New-Mailbox cmdlet and it does not accept wildcard characters. You can use Get-Help when examining the parameters for any cmdlet to determine whether or not they support these settings.

You could run Get-HelpNew-MailboxExamples to determine the syntax required to create a secure string password object and how to use it to create a mailbox. This is also covered in detail in the recipe entitled Adding, modifying, and removing mailboxes in Chapter 3, Managing Recipients.

There's more...

There will be times when you'll need to search for a cmdlet without knowing its full name. In this case, there are a couple of commands you can use to find the cmdlets you are looking for.

To find all cmdlets that contain the word "mailbox", you can use a wildcard, as shown in the following command:

Get-Command *Mailbox*

You can use the -Verb parameter to find all cmdlets starting with a particular verb:

Get-Command -Verb Set

To search for commands that use a particular noun, specify the name with the -Noun parameter:

Get-Command -Noun Mailbox

The Get-Command cmdlet is a built-in PowerShell core cmdlet, and it will return commands from both Windows PowerShell as well as the Exchange Management Shell. The Exchange Management Shell also adds a special function called Get-Ex command that will return only Exchange-specific commands.

In addition to getting cmdlet help for cmdlets, you can use GetHelp to view supplementary help files that explain general PowerShell concepts that focus primarily on scripting. To display the help file for a particular concept, type Get-Helpabout_ followed by the concept name. For example, to view the help for the core PowerShell commands, type the following:

Get-Help about_Core_Commands

You can view the entire list of conceptual help files using the following command:

Get-Help about_*

Don't worry about trying to memorize all the Exchange or PowerShell cmdlet names. As long as you can remember GetCommand and Get-Help, you can search for commands and figure out the syntax to do just about anything.

Getting help with cmdlets and functions

One of the things that can be confusing at first is the distinction between cmdlets and functions. When you launch the Exchange Management Shell, a remote PowerShell session is initiated to an Exchange server and specific commands, called proxy functions, are imported into your shell session. These proxy functions are essentially just blocks of code that have a name, such as GetMailbox, and that correspond to the compiled cmdlets installed on the server. This is true even if you have a single server and when you are running the shell locally on a server.

When you run the Get-Mailbox function from the shell, data is passed between your machine and the Exchange server through a remote PowerShell session. The Get-Mailbox cmdlet is actually executing on the remote Exchange server, and the results are being passed back to your machine. One of the benefits of this is that it allows you to run the cmdlets remotely regardless of whether your servers are on-premise or in the cloud. Additionally, this core change in the tool set is what allows Exchange 2010 and 2013 to implement its new security model by allowing and restricting which cmdlets administrators and end users can actually use through the shell or the web-based control panel.

We'll get into the details of all this throughout the remaining chapters in the book. The bottom line is that, for now, you need to understand that, when you are working with the help system, the Exchange 2013 cmdlets will show up as functions and not as cmdlets.

Consider the following command and the output:

Here we are running GetCommand against a PowerShell v3 core cmdlet. Notice that the CmdletType shows that this is a Cmdlet.

Now try the same thing for the Get-Mailbox cmdlet:

As you can see, the CommandType for the Get-Mailbox cmdlet shows that it is actually a Function. So, there are a couple of key points to take away from this. First, throughout the course of this book, we will refer to the Exchange 2013 cmdlets as cmdlets, even though they will show up as functions when running GetCommand. Second, keep in mind that you can run Get-Help against any function name, such as Get-Mailbox, and you'll still get the help file for that cmdlet. But if you are unsure of the exact name of a cmdlet, use Get-Command to perform a wildcard search as an aid in the discovery process. Once you've determined the name of the cmdlet you are looking for, you can run GetHelp against that cmdlet for complete details on how to use it.

Try using the help system before going to the Internet to find answers. You'll find that the answers to most of your questions are already documented within the built-in cmdlet help.

See also

  • The Understanding command syntax and parameters recipe

  • The Manually configuring remote PowerShell connections recipe in Chapter 2, Exchange Management Shell Common Tasks

  • The Working with Role Based Access Control (RBAC) recipe in Chapter 10, Exchange Security

Understanding command syntax and parameters


Windows PowerShell provides a large number of built-in cmdlets that perform specific operations. The Exchange Management Shell adds an additional set of PowerShell cmdlets used specifically for managing Exchange. We can also run these cmdlets interactively in the shell, or through automated scripts. When executing a cmdlet, parameters can be used to provide information, such as which mailbox or server to work with, or which attribute of those objects should be modified. In this recipe, we'll take a look at basic PowerShell command syntax and how parameters are used with cmdlets.

How to do it...

When running a PowerShell command, you type the cmdlet name, followed by any parameters required. Parameter names are preceded by a hyphen (-) followed by the value of the parameter. Let's start with a basic example. To get mailbox information for a user named testuser, use the following command syntax:

Get-Mailbox –Identity testuser

Alternatively, the following syntax also works and provides the same output, because the –Identity parameter is a positional parameter:

Get-Mailbox testuser

Most cmdlets support a number of parameters that can be used within a single command. We can use the following command to modify two separate settings on the testuser mailbox:

Set-Mailbox testuser –MaxSendSize 5mb –MaxReceiveSize 5mb

How it works...

All cmdlets follow a standard verb-noun naming convention. For example, to get a list of mailboxes you use the Get-Mailbox cmdlet. You can change the configuration of a mailbox using the Set-Mailbox cmdlet. In both examples, the verb (Get or Set) is the action you want to take on the noun (Mailbox). The verb is always separated from the noun using the hyphen (-) character. With the exception of a few Exchange Management Shell cmdlets, the noun is always singular.

Cmdlet names and parameters are not case sensitive. You can use a combination of upper and lowercase letters to improve the readability of your scripts, but it is not required.

Parameter input is either optional or required, depending on the parameter and cmdlet you are working with. You don't have to assign a value to the c parameter since it is not required when running the Get-Mailbox cmdlet. If you simply run Get-Mailbox without any arguments, the first 1,000 mailboxes in the organization will be returned.

Tip

If you are working in a large environment with more than 1,000 mailboxes, you can run the Get-Mailbox cmdlet setting the -ResultSize parameter to Unlimited to retrieve all of the mailboxes in your organization.

Notice that in the first two examples we ran Get-Mailbox for a single user. In the first example, we used the -Identity parameter, but in the second example we did not. The reason we don't need to explicitly use the -Identity parameter in the second example is because it is a positional parameter. In this case, -Identity is in position 1, so the first argument received by the cmdlet is automatically bound to this parameter. There can be a number of positional parameters supported by a cmdlet, and they are numbered starting from one. Other parameters that are not positional are known as named parameters, meaning we need to use the parameter name to provide input for the value.

The -Identity parameter is included with most of the Exchange Management Shell cmdlets, and it allows you to classify the object you want to take an action on.

Tip

The -Identity parameter used with the Exchange Management Shell cmdlets can accept different value types. In addition to the alias, the following values can be used: ADObjectID, Distinguished name, Domain\Username, GUID, LegacyExchangeDN, SmtpAddress, and User principal name (UPN).

Unlike the Get-Mailbox cmdlet, the -Identity parameter is required when you are modifying objects, and we saw an example of this when running the Set-Mailbox cmdlet. This is because the cmdlet needs to know which mailbox it should modify when the command is executed. When you run a cmdlet without providing input for a required parameter, you will be prompted to enter the information before execution.

Tip

In order to determine whether a parameter is required, named, or positional, supports wildcards, or accepts input from the pipeline, you can use the Get-Help cmdlet which is covered in the next recipe in this chapter.

Multiple data types are used for input depending on the parameter you are working with. Some parameters accept string values, while others accept integers or Boolean values. Boolean parameters are used when you need to set a parameter value to either true or false. PowerShell provides built-in shell variables for each of these values using the $true and $false automatic variables.

Note

For a complete list of PowerShell v3 automatic variables, run Get-Help about_automatic_variables. Also see Appendix A, Common Shell Information, for a list of automatic variables added by the Exchange Management Shell.

For example, you can enable or disable a send connector using the Set-SendConnector cmdlet with the -Enabled parameter:

Set-SendConnector Internet -Enabled $false

Switch parameters don't require a value. Instead they are used to turn something on or off, or to either enable or disable a feature or setting. One common example of when you might use a switch parameter is when creating an archive mailbox for a user:

Enable-Mailbox testuser -Archive

PowerShell also provides a set of common parameters that can be used with every cmdlet. Some of the common parameters, such as the risk mitigation parameters (-Confirm and -Whatif), only work with cmdlets that make changes.

Tip

For a complete list of common parameters, run Get-Helpabout_CommonParameters.

Risk mitigation parameters allow you to preview a change or confirm a change that may be destructive. If you want to see what will happen when executing a command without actually executing it, use the -WhatIfparameter :

When making a change, such as removing a mailbox, you'll be prompted for confirmation, as shown in the following screenshot:

To suppress this confirmation set the -Confirm parameter to false:

Remove-Mailbox testuser -Confirm:$false

Notice here that when assigning the $false variable to the -Confirm parameter, we had to use a colon immediately after the parameter name and then the Boolean value. This is different to how we assigned this value earlier with the -Enabled parameter when using the Set-SendConnector cmdlet. Remember that the -Confirm parameter always requires this special syntax, and while most parameters that accept a Boolean value generally do not require this, it depends on the cmdlet with which you are working. Fortunately, PowerShell has a great built-in help system that we can use when we run into these inconsistencies. When in doubt, use the help system, which is covered in detail in the next recipe.

Cmdlets and parameters support tab completion. You can start typing the first few characters of a cmdlet or a parameter name and hit the tab key to automatically complete the name or tab through a list of available names. This is very helpful in terms of discovery and can serve as a bit of a time saver.

In addition, you only need to type enough characters of a parameter name to differentiate it from another parameter name. The following command using a partial parameter name is completely valid:

Set-Mailbox -id testuser –Office Sales

Here we've used id as a shortcut for the -Identity parameter. The cmdlet does not provide any other parameters that start with id, so it automatically assumes you want to use the -Identity parameter.

Another helpful feature that some parameters support is the use of wildcards. When running the Get-Mailbox cmdlet, the -Identity parameter can be used with wildcards to return multiple mailboxes that match a certain pattern:

Get-Mailbox -id t*

In this example, all mailboxes starting with the letter "t" will be returned. Although this is fairly straightforward, you can refer to the help system for details on using wildcard characters in PowerShell by running Get-Help about_Wildcards.

There's more...

Parameter values containing a space need to be enclosed in either single or double quotation marks. The following command would retrieve all of the mailboxes in the Sales Users OU in Active Directory. Notice that since the OU name contains a space, it is enclosed in single quotes:

Get-Mailbox -OrganizationalUnit 'contoso.com/Sales Users/Phoenix'

Use double quotes when you need to expand a variable within a string:

$City = 'Phoenix'
Get-Mailbox -OrganizationalUnit "contoso.com/Sales Users/$City"

You can see here that we first create a variable containing the name of the city, which represents a sub OU under Sales Users. Next, we include the variable inside the string used for the organizational unit when running the Get-Mailbox cmdlet. PowerShell automatically expands the variable name inside the double quoted string where the value should appear and all mailboxes inside the Phoenix OU are returned by the command.

Tip

Quoting rules are documented in detail in the PowerShell help system. Run Get-Helpabout_Quoting_Rules for more information.

See also

  • The Using the help system recipe

  • The Working with variables and objects recipe

Understanding the pipeline


The single most important concept in PowerShell is the use of its flexible, object-based pipeline. You may have used pipelines in Unix-based shells, or when working with the cmd.exe command prompt. The concept of pipelines is similar to that of sending the output from one command to another. But, instead of passing plain text, PowerShell works with objects, and we can accomplish some very complex tasks in just a single line of code. In this recipe, you'll learn how to use pipelines to string together multiple commands and build powerful one-liners.

How to do it...

The following pipeline command would set the office location for every mailbox in the DB1 database:

Get-Mailbox -Database DB1 | Set-Mailbox -Office Headquarters

How it works...

In a pipeline, you separate a series of commands using the pipe (|) character. In the previous example, the Get-Mailbox cmdlet returns a collection of mailbox objects. Each mailbox object contains several properties that contain information such as the name of the mailbox, the location of the associated user account in Active Directory, and more. The Set-Mailbox cmdlet is designed to accept input from the Get-Mailbox cmdlet in a pipeline, and with one simple command we can pass along an entire collection of mailboxes that can be modified in one operation.

You can also pipe output to filtering commands, such as the Where-Object cmdlet. In this example, the command retrieves only the mailboxes with a MaxSendSize equal to 10 megabytes:

Get-Mailbox | Where-Object{$_.MaxSendSize -eq 10mb}

The code that the Where-Object cmdlet uses to perform the filtering is enclosed in curly braces ({}). This is called a script block, and the code within this script block is evaluated for each object that comes across the pipeline. If the result of the expression is evaluated as true, the object is returned; otherwise, it is ignored. In this example, we access the MaxSendSize property of each mailbox using the $_ object, which is an automatic variable that refers to the current object in the pipeline. We use the equals (-eq) comparison operator to check that the MaxSendSize property of each mailbox is equal to 10 megabytes. If so, only those mailboxes are returned by the command.

Tip

Comparison operators allow you to compare results and find values that match a pattern. For a complete list of comparison operators, run Get-Helpabout_Comparison_Operators.

When running this command, which can also be referred to as a one-liner, each mailbox object is processed one at a time using stream processing. This means that as soon as a match is found, the mailbox information is displayed on the screen. Without this behavior, you would have to wait for every mailbox to be found before seeing any results. This may not matter if you are working in a very small environment, but without this functionality in a large organization with tens of thousands of mailboxes, you would have to wait a long time for the entire result set to be collected and returned.

One other interesting thing to note about the comparison being done inside our Where-Object filter is the use of the mb multiplier suffix. PowerShell natively supports these multipliers and they make it a lot easier for us to work with large numbers. In this example, we've used 10mb, which is the equivalent of entering the value in bytes because behind the scenes, PowerShell is doing the math for us by replacing this value with 1024*1024*10. PowerShell provides support for the following multipliers: kb, mb, gb, tb, and pb.

There's more...

You can use advanced pipelining techniques to send objects across the pipeline to other cmdlets that do not support direct pipeline input. For example, the following one-liner adds a list of users to a group:

Get-User | 
  Where-Object{$_.title -eq "Exchange Admin"} | Foreach-Object{
      Add-RoleGroupMember -Identity "Organization Management" `
      -Member $_.name
  }

This pipeline command starts off with a simple filter that returns only the users that have their title set to "Exchange Admin". The output from that command is then piped to the ForEach-Object cmdlet that processes each object in the collection. Similar to the Where-Object cmdlet, the ForEach-Object cmdlet processes each item from the pipeline using a script block. Instead of filtering, this time we are running a command for each user object returned in the collection and adding them to the "Organization Management" role group.

Using aliases in pipelines can be helpful because it reduces the number of characters you need to type. Take a look at the following command where the previous command is modified to use aliases:

Get-User | 
  ?{$_.title -eq "Exchange Admin"} | %{
    Add-RoleGroupMember -Identity "Organization Management" `
    -Member $_.name
  }

Notice the use of the question mark (?) and the percent sign (%) characters. The ? character is an alias for the Where-Object cmdlet, and the % character is an alias for the ForEach-Object cmdlet. These cmdlets are used heavily, and you'll often see them used with these aliases because it makes the commands easier to type.

Tip

You can use the Get-Alias cmdlet to find all of the aliases currently defined in your shell session and the New-Alias cmdlet to create custom aliases.

The Where-Object and ForEach-Object cmdlets have additional aliases. Here's another way you could run the previous command:

Get-User | 
  where{$_.title -eq "Exchange Admin"} | foreach{
    Add-RoleGroupMember -Identity "Organization Management" `
    -Member $_.name
  }

Use aliases when you're working interactively in the shell to speed up your work and keep your commands concise. You may want to consider using the full cmdlet names in production scripts to avoid confusing others who may read your code.

See also

  • The Looping through items recipe

  • The Creating custom objects recipe

  • The Dealing with concurrent pipelines in remote PowerShell recipe in Chapter 2, Exchange Management Shell Common Tasks

Working with variables and objects


Every scripting language makes use of variables as placeholders for data, and PowerShell is no exception. You'll need to work with variables often to save temporary data to an object so you can work with it later. PowerShell is very different from other command shells in that everything you touch is, in fact, a rich object with properties and methods. In PowerShell, a variable is simply an instance of an object just like everything else. The properties of an object contain various bits of information depending on the type of object you're working with. In this recipe we'll learn to create user-defined variables and work with objects in the Exchange Management Shell.

How to do it...

To create a variable that stores an instance of the testuser mailbox, use the following command:

$mailbox = Get-Mailbox testuser

How it works...

To create a variable, or an instance of an object, you prefix the variable name with the dollar sign ($). To the right of the variable name, use the equals (=) assignment operator, followed by the value or object that should be assigned to the variable. Keep in mind that the variables you create are only available during your current shell session and will be destroyed when you close the shell.

Let's look at another example. To create a string variable that contains an e-mail address, use the following command:

$email = "testuser@contoso.com"

Tip

In addition to user-defined variables, PowerShell also includes automatic and preference variables. To learn more, run Get-Helpabout_Automatic_Variables and Get-Helpabout_Preference_Variables.

Even a simple string variable is an object with properties and methods. For instance, every string has a Length property that will return the number of characters that are in the string:

[PS] C:\>$email.length
20

When accessing the properties of an object, you can use dot notation to reference the property with which you want to work. This is done by typing the object name, then a period, followed by the property name, as shown in the previous example. You access methods in the same way, except that the method names always end with parenthesis ().

The string data type supports several methods, such as Substring, Replace, and Split. The following example shows how the Split method can be used to split a string:

[PS] C:\>$email.Split("@")
testuser
contoso.com

You can see here that the Split method uses the "@" portion of the string as a delimiter and returns two substrings as a result.

Tip

PowerShell also provides a -Split operator that can split a string into one or more substrings. Run Get-Helpabout_Split for details.

There's more...

At this point, you know how to access the properties and methods of an object, but you need to be able to discover and work with these members. To determine which properties and methods are accessible on a given object, you can use the Get-Member cmdlet, which is one of the key discovery tools in PowerShell along with Get-Help and Get-Command.

To retrieve the members of an object, pipe the object to the Get-Member cmdlet. The following command will retrieve all of the instance members of the $mailbox object we created earlier:

$mailbox | Get-Member

Tip

To filter the results returned by Get-Member, use the -MemberType parameter to specify whether the type should be a Property or a Method.

Let's take a look at a practical example of how we could use Get-Member to discover the methods of an object. Imagine that each mailbox in our environment has had a custom MaxSendSize restriction set and we need to record the value for reporting purposes. When accessing the MaxSendSize property, the following information is returned:

[PS] C:\>$mailbox.MaxSendSize
IsUnlimited Value
----------- -----
False       10 MB (10,485,760 bytes)

We can see here that the MaxSendSize property actually contains an object with two properties: IsUnlimited and Value. Based on what we've learned, we should be able to access the information for the Value property using dot notation:

[PS] C:\>$mailbox.MaxSendSize.Value
10 MB (10,485,760 bytes)

That works, but the information returned contains not only the value in megabytes, but also the total bytes for the MaxSendSize value. For the purpose of what we are trying to accomplish, we only need the total megabytes. Let's see if this object provides any methods that can help us out with this using Get-Member:

From the output shown in the previous screenshot, we can see this object supports several methods that can be used convert the value. To obtain the MaxSendSize value in megabytes, we can call the ToMB method:

[PS] C:\>$mailbox.MaxSendSize.Value.ToMB()
10

In a traditional shell, you would have to perform complex string parsing to extract this type of information, but PowerShell and the .NET Framework make this much easier. As you'll see over time, this is one of the reasons why PowerShell's object-based nature really outshines a typical text-based command shell.

An important thing to point about this last example is that it would not work if the mailbox had not had a custom MaxSendSize limitation configured. Nevertheless, this provides a good illustration of the process you'll want to use when you're trying to learn about an object's properties or methods.

Variable expansion in strings

As mentioned in the Understanding command syntax and parameters recipe in this chapter, PowerShell uses quoting rules to determine how variables should be handled inside a quoted string. When enclosing a simple variable inside a double-quoted string, PowerShell will expand that variable and replace the variable with the value of the string. Let's take a look at how this works by starting off with a simple example:

[PS] C:\>$name = "Bob"
[PS] C:\> "The user name is $name"
The user name is Bob

This is pretty straightforward. We stored the string value of "Bob" inside the $name variable. We then include the $name variable inside a double-quoted string that contains a message. When we hit return, the $name variable is expanded and we get back the message we expect to see on the screen.

Now let's try this with a more complex object. Let's say that we want to store an instance of a mailbox object in a variable and access the PrimarySmtpAddress property inside the quoted string:

[PS] C:\>$mailbox = Get-Mailbox testuser
[PS] C:\>"The email address is $mailbox.PrimarySmtpAddress"
The email address is test user.PrimarySmtpAddress

Notice here that when we try to access the PrimarySmtpAddress property of our mailbox object inside the double-quoted string, we're not getting back the information that we'd expect. This is a very common stumbling block when it comes to working with objects and properties inside strings. We can get around this using sub-expression notation. This requires that you enclose the entire object within $() characters inside the string:

[PS] C:\>"The email address is $($mailbox.PrimarySmtpAddress)"
The email address is testuser@contoso.com

Using this syntax, the PrimarySmtpAddress property of the $mailbox object is properly expanded and the correct information is returned. This technique will be useful later when extracting data from objects and generating reports or logfiles.

Strongly typed variables

PowerShell will automatically try to select the correct data type for a variable based on the value being assigned to it. You don't have to worry about doing this yourself, but we do have the ability to explicitly assign a type to a variable if needed. This is done by specifying the data type in square brackets before the variable name:

[string]$a = 32

Here we've assigned the value of 32 to the $a variable. Had we not strongly typed the variable using the [string] type shortcut, $a would have been created using the Int32 data type, since the value we assigned was a number that was not enclosed in single or double quotes. Take a look at the following screenshot:

As you can see here, the $var1 variable is initially created without any explicit typing. We use the GetType() method, which can be used on any object in the shell, to determine the data type of $var1. Since the value assigned was a number not enclosed in quotes, it was created using the Int32 data type. When using the [string] type shortcut to create $var2 with the same value, you can see that it has now been created as a string.

It is good to have an understanding of data types because when building scripts that return objects, you may need to have some control over this. For example, you may want to report on the amount of free disk space on an Exchange server. If we store this value in the property of a custom object as a string, we lose the ability to sort on that value. There are several examples throughout the book that use this technique.

See Appendix A, Common Shell Information, for a listing of commonly-used type shortcuts.

Formatting output


One of the most common PowerShell questions is how to get information returned from commands in the desired output on the screen. In this recipe, we'll take a look at how you can output data from commands and format that information for viewing on the screen.

How to do it...

To change the default output and view the properties of an object in list format, pipe the command to the Format-List cmdlet:

Get-Mailbox testuser | Format-List

To view specific properties in table format, supply a comma-separated list of property names as parameters, as shown next when using Format-Table:

Get-Mailbox testuser | Format-Table name,alias

How it works...

When you run the Get-Mailbox cmdlet, you only see the Name, Alias, ServerName, and ProhibitSendQuota properties of each mailbox in a table format. This is because the Get-Mailbox cmdlet receives its formatting instructions from the exchange.format.ps1xml file located in the Exchange server bin directory.

PowerShell cmdlets use a variety of formatting files that usually include a default view with only a small subset of predefined properties. When you need to override the default view, you can use Format-List and Format-Table cmdlets.

You can also select specific properties with Format-List, just as we saw when using the Format-Table cmdlet. The difference is, of course, that the output will be displayed in list format.

Let's take a look at the output from the Format-Table cmdlet, as shown previously:

As you can see here, we get both properties of the mailbox formatted as a table.

When using Format-Table cmdlet, you may find it useful to use the -Autosize parameter to organize the columns based on the width of the data:

This command selects the same properties as our previous example, but this time we are using the -Autosize parameter and the columns are adjusted to use only as much space on the screen as is needed. Remember, you can use the ft alias instead of typing the entire Format-Table cmdlet name. You can also use the fl alias for the Format-List cmdlet. Both of these aliases can keep your commands concise and are very convenient when working interactively in the shell.

There's more…

One thing to keep in mind is that you never want to use the Format-* cmdlets in the middle of a pipeline since most other cmdlets will not understand what to do with the output. The Format-* cmdlets should normally be the last thing you do in a command unless you are sending the output to a printer or a text file.

To send formatted output to a text file, you can use the Out-File cmdlet. In the following command, the Format-List cmdlet uses the asterisk (*) character as a wildcard and exports all of the property values for the mailbox to a text file:

Get-Mailbox testuser | fl * | Out-File c:\mb.txt

To add data to the end of an existing file, use the -Append parameter with the Out-File cmdlet. Even though we're using the Out-File cmdlet here, the traditional cmd output redirection operators such as > and >> can still be used. The difference is that the cmdlet gives you a little more control over the output method and provides parameters for tasks, including setting the encoding of the file.

You can sort the output of a command using the Sort-Object cmdlet. For example, this command will display all mailbox databases in alphabetical order:

Get-MailboxDatabase | sort name | ft name

We are using the sort alias for the Sort-Object cmdlet specifying name as the property we want to sort. To reverse the sort order, use the descending switch parameter:

Get-MailboxDatabase | sort name -desc | ft name

See also

  • The Understanding the pipeline recipe

  • The Exporting reports to text and CSV files recipe in Chapter 2, Exchange Management Shell Common Tasks

Left arrow icon Right arrow icon

Key benefits

  • Newly updated and improved for Exchange Server 2013 and PowerShell 3
  • Learn how to write scripts and functions, schedule scripts to run automatically, and generate complex reports with PowerShell
  • Manage and automate every element of Exchange Server 2013 with PowerShell such as mailboxes, distribution groups, and address lists

Description

Microsoft Exchange Server 2013 is a complex messaging system. Windows PowerShell 3 can be used in conjunction with Exchange Server 2013 to automate and manage routine and complex tasks to save time, money, and eliminate errors.Microsoft Exchange Server 2013 PowerShell Cookbook: Second Edition offers more than 120 recipes and solutions to everyday problems and tasks encountered in the management and administration of Exchange Server. If you want to write scripts that help you create mailboxes, monitor server resources, and generate detailed reports, then this Cookbook is for you. This practical guide to Powershell and Exchange Server 2013 will help you automate and manage time-consuming and reoccurring tasks quickly and efficiently. Starting by going through key PowerShell concepts and the Exchange Management Shell, this book will get you automating tasks that used to take hours in no time.With practical recipes on the management of recipients and mailboxes as well as distribution groups and address lists, this book will save you countless hours on repetitive tasks. Diving deeper, you will then manage your mailbox database, client access, and your transport servers with simple but effective scripts.This book finishes with advanced recipes on Exchange Server problems such as server monitoring as well as maintaining high availability and security. If you want to control every aspect of Exchange Server 2013 and learn how to save time with PowerShell, then this cookbook is for you.

Who is this book for?

This Cookbook is for messaging professionals who want to learn how to build real-world scripts with Windows PowerShell 3 and the Exchange Management Shell. If you are a network or systems administrator responsible for managing and maintaining Exchange Server 2013 you will find this highly useful. Only basic knowledge of Exchange Server and PowerShell are required to make the most of this book.

What you will learn

  • New features and capabilities of PowerShell 3 and Exchange Server 2013
  • Get to grips with the core PowerShell concepts required to master the Exchange Management Shell such as pipelining, working with objects, formatting output, and writing scripts
  • Use simple PowerShell scripts and commands for powerful effect
  • Monitor server resources including CPU, memory, disk, event logs, and more using PowerShell
  • Generate detailed reports, send the output of commands in e-mail messages, and schedule scripts to run automatically
  • Import, export, move mailboxes, and delete messages from mailboxes using the command line
  • Configure transport server settings such as mail relay, tracking logs, transport rules, delivery reports, and more
  • Manage mailbox and public folder databases
Estimated delivery fee Deliver to Lithuania

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : May 22, 2013
Length: 504 pages
Edition : 2nd
Language : English
ISBN-13 : 9781849689427
Vendor :
Microsoft
Concepts :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Lithuania

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

Publication date : May 22, 2013
Length: 504 pages
Edition : 2nd
Language : English
ISBN-13 : 9781849689427
Vendor :
Microsoft
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 136.97
Windows Server 2012 Automation with PowerShell Cookbook
€45.99
Microsoft Exchange Server 2013 PowerShell Cookbook: Second Edition
€48.99
Microsoft Exchange 2013 Cookbook
€41.99
Total 136.97 Stars icon
Banner background image

Table of Contents

13 Chapters
PowerShell Key Concepts Chevron down icon Chevron up icon
Exchange Management Shell Common Tasks Chevron down icon Chevron up icon
Managing Recipients Chevron down icon Chevron up icon
Managing Mailboxes Chevron down icon Chevron up icon
Distribution Groups and Address Lists Chevron down icon Chevron up icon
Mailbox Database Management Chevron down icon Chevron up icon
Managing Client Access Chevron down icon Chevron up icon
Managing Transport Service Chevron down icon Chevron up icon
High Availability Chevron down icon Chevron up icon
Exchange Security Chevron down icon Chevron up icon
Compliance and Audit Logging Chevron down icon Chevron up icon
Server Monitoring and Troubleshooting Chevron down icon Chevron up icon
Scripting with the Exchange Web Services Managed API Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.8
(10 Ratings)
5 star 80%
4 star 20%
3 star 0%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




sultrypoet Feb 20, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Good resource.
Amazon Verified review Amazon
AD Aug 22, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great book.
Amazon Verified review Amazon
Nicolas Blank Aug 30, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
If you're an administrator or a consultant needing to learn PowerShell in the context of Exchange 2013, then this book is a must have. The authors teach PowerShell in the context of Exchange tasks, allowing the reader to expand their skills incrementally, or jump into a specific chapter and pickup new skills per task.If you're a total Newbie to PowerShell, I strongly suggest starting with Chapter one before you bounce around to the other chapters.If you're looking for PowerShell help for Exchange 2010, then consider looking at the first edition of this book.
Amazon Verified review Amazon
itsmygame Aug 23, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Being a fan of the Exchange Management Shell I am very impressed with how this book delves into all the commands & syntaxes available. The examples are excellent too and the book emphasises on the differences between previous versions of Exchange and where improvements in the Shell cmdlets have been made. This is the definitive source on Exchange Shell Management for me. Thanks.
Amazon Verified review Amazon
Dnacool1 Dec 01, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Received as expected.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela