Chapter 4. Using Exchange Management Shell

Microsoft Exchange Server 2013 includes Exchange Management Shell to complement the expanding role of Exchange Server administrators and developers. Exchange Management Shell is an extensible command-line environment for Exchange Server that builds on the existing framework provided by Windows PowerShell. When you install Exchange Server 2013 on a server, or when you install the Exchange Server management tools on a workstation, you install Exchange Management Shell as part of the process. This chapter introduces Windows PowerShell and its features and then details the available commands and options of Exchange Management Shell, which has changed considerably from its earlier implementations.

Using Windows PowerShell

Anyone with a UNIX background is probably familiar with the concept of a command shell. Most UNIX-based operating systems have several full-featured command shells available, such as C Shell and Bourne Shell (SH). Although Microsoft Windows operating systems have always had a command-line environment, they’ve lacked a full-featured command shell until Windows PowerShell was introduced.

Introducing Windows PowerShell

Not unlike the less sophisticated Windows command prompt, the UNIX command shells operate by executing built-in commands, external commands, and command-line utilities and then returning the results in an output stream as text. The output stream can be manipulated in various ways, including redirecting the output stream so that it can be used as input for another command. This process of redirecting one command’s output to another command’s input is called piping, and it is a widely used shell-scripting technique.

C Shell is one of the more sophisticated UNIX shells. In many respects, C Shell is a marriage of some of the best features of the C programming language and a full-featured UNIX shell environment. Windows PowerShell takes the idea of a full-featured command shell built on a programming language a step further. It does this by implementing a scripting language based on C# and an object model based on the Microsoft .NET Framework.

Basing the scripting language for Windows PowerShell on C# ensures that the scripting language can be easily understood by current C# developers and also allows new developers who work with PowerShell to advance to C#. Using an object model based on the .NET Framework allows Windows PowerShell to pass complete objects and all their properties as output from one command to another. The ability to redirect objects is extremely powerful and allows for a much more dynamic manipulation of a result set. For example, not only can you get the name of a particular user, but you can also get the entire related user object. You can then manipulate the properties of this user object as necessary by referring to the properties you want to work with by name.

Running and using Windows PowerShell

Windows PowerShell is built into Windows 8, Windows Server 2012, and later releases of the Windows operating system. Windows PowerShell has both a command-line environment and a graphical environment for running commands and scripts. The PowerShell console (powershell.exe) is available as a 32-bit or 64-bit environment for working with PowerShell at the command line. On 32-bit versions of Windows, you’ll find the 32-bit executable in the %SystemRoot%System32WindowsPowerShellv1.0 directory. On 64-bit versions of Windows, you’ll find the 32-bit executable in the %SystemRoot%SysWow64WindowsPowerShellv1.0 directory and the 64-bit executable in the %SystemRoot%System32WindowsPowerShellv1.0 directory.

With Windows 8 or later and Windows Server 2012 RTM or R2, you can start the PowerShell console by using the Apps Search box. Type powershell in the Apps Search box, and then press Enter. Or you can tap or click Start and then choose Windows PowerShell. With Windows 7 and Windows Server 2008 R2, you can start Exchange Management Shell by tapping or clicking Start, pointing to All Programs, tapping or clicking Microsoft Exchange Server 2013, and then tapping or clicking Exchange Management Shell.

Important

Exchange 2013 is optimized for 64-bit interfaces, and the related management tools can be run only on 64-bit versions of Windows. On 64-bit systems, the 64-bit version of PowerShell is started by default and the 32-bit PowerShell console is labeled as Windows PowerShell (x86). Don’t use Windows PowerShell (x86) when working with Exchange 2013 from your management computer.

Real World

You can start Windows PowerShell from a Windows command shell (cmd.exe) by typing powershell. To exit Windows PowerShell and return to the command prompt, type exit. However, if you start Windows PowerShell from within a 32-bit command shell, the 32-bit Windows PowerShell console will be started—and that will cause problems when working with Exchange 2013. The 64-bit command shell is stored in the %SystemRoot%System32 directory. The 32-bit command shell is stored in the %SystemRoot%SysWow64 directory.

Usually, when the shell starts, you will see a message similar to the following:

Windows PowerShell
Copyright (C) 2012 Microsoft Corporation. All rights reserved.

You can disable this message by starting the shell with the -Nologo parameter, such as:

powershell -nologo

Figure 4-1 shows a PowerShell window. Typically, the window is 120 characters wide and displays 50 lines of text by default. When additional text is to be displayed in the window or you enter commands and the PowerShell console’s window is full, the current text is displayed in the window and prior text is scrolled up. If you want to pause the display temporarily when a command is writing output, press Ctrl+S. Afterward, press Ctrl+S to resume or Ctrl+C to terminate execution.

A screen shot of the Windows PowerShell console.
Figure 4-1. Working with Windows PowerShell.

When you start Windows PowerShell, the working environment is loaded automatically. Many features of the working environment come from profiles, which are a type of script that run when you start PowerShell. However, the working environment is also determined by imported modules, snap-ins, providers, command paths, file extensions, and file associations.

You can start Windows PowerShell without loading profiles using the -Noprofile parameter, such as:

powershell -noprofile

Whenever you work with scripts, you need to keep in mind the current execution policy and whether signed scripts are required. Execution policy controls whether and how you can run configuration files and scripts. Execution policy is a built-in security feature of Windows PowerShell that is set on a per-user basis in the Windows registry. Although the default configuration depends on which operating system and edition are installed, you can quickly determine the execution policy by typing get-executionpolicy at the PowerShell prompt.

The available execution policies, from least secure to most secure, are:

  • BypassThis policy bypasses warnings and prompts when scripts run. It is intended for use with programs that have their own security model or when a PowerShell script is built into a larger application.

  • Unrestricted. This policy allows all configuration files and scripts to run whether they are from local or remote sources and regardless of whether they are signed or unsigned. However, if you run a configuration file or script from a remote resource, you are prompted with a warning that the file comes from a remote resource before the configuration file is loaded or the script runs.

  • RemoteSigned. This policy requires all configuration files and scripts from remote sources to be signed by a trusted publisher. Configuration files and scripts on the local computer do not need to be signed. PowerShell does not prompt you with a warning before running scripts from trusted publishers.

  • AllSigned. This policy requires all configuration files and scripts from all sources—whether local or remote—to be signed by a trusted publisher. Because of this requirement, configuration files and scripts on the local computer must be signed as configuration files, and scripts from remote computers must be signed. PowerShell prompts you with a warning before running scripts from trusted publishers.

  • Restricted. This policy prevents PowerShell from loading configuration files and scripts. This means all configuration files and scripts, regardless of whether they are signed or unsigned. Because a profile is a type of script, profiles are not loaded either.

  • Undefined. This policy removes the execution policy that is set for the current user scope. As a result, the execution policy set in Group Policy or for the LocalMachine scope is effective. If execution policy in all scopes is set to Undefined, the default execution policy, Restricted, is the effective policy.

Important

By default, when you set execution policy, you are using the LocalMachine scope, which affects all users of the computer. You also can set the scope to CurrentUser so that the execution policy level is applied only to the currently logged on user.

You can use the Set-ExecutionPolicy cmdlet to change the preference for the execution policy. Changes to the policy are written to the registry. However, if the Turn On Script Execution setting in Group Policy is enabled for the computer or user, the user preference is written to the registry, but it is not effective, and Windows PowerShell displays a message explaining the conflict. You cannot use Set-ExecutionPolicy to override a group policy, even if the user preference is more restrictive than the policy setting.

To set the execution policy to require that all scripts have a trusted signature to execute, type the following command:

set-executionpolicy allsigned

To set the execution policy so that scripts downloaded from the web execute only if they are signed by a trusted source, type:

set-executionpolicy remotesigned

To set the execution policy to run scripts regardless of whether they have a digital signature and work in an unrestricted environment, type the following command:

set-executionpolicy unrestricted

The change occurs immediately and is applied to the local console or application session. Because the change is written to the registry, the new execution policy will be used whenever you work with PowerShell.

Running and using cmdlets

Windows PowerShell introduces the concept of a cmdlet (pronounced commandlet). A cmdlet is the smallest unit of functionality in Windows PowerShell. You can think of a cmdlet as a built-in command. Rather than being highly complex, most cmdlets are quite simple and have a small set of associated properties.

You use cmdlets the same way you use any other commands and utilities. Cmdlet names are not case sensitive. This means you can use a combination of both uppercase and lowercase characters. After starting Windows PowerShell, you can type the name of the cmdlet at the prompt, and it will run in much the same way as a command-line command.

For ease of reference, cmdlets are named using verb-noun pairs. As Table 4-1 shows, the verb tells you what the cmdlet does in general. The noun tells you what specifically the cmdlet works with. For example, the Get-Variable cmdlet gets a named Windows PowerShell environment variable and returns its value. If you don’t specify which variable to get as a parameter, Get-Variable returns a list of all Windows PowerShell environment variables and their values.

Table 4-1. Common verbs associated with cmdlets and their meanings

CMDLET VERB

USAGE

Add

Adds an instance of an item, such as a history entry or snap-in

Clear

Removes the contents of an item, such as an event log or variable value

New

Creates a new instance of an item, such as a new mailbox

Remove

Removes an instance of an item, such as a mailbox

Enable

Enables a setting or mail-enables a recipient

Disable

Disables an enabled setting or mail-disables a recipient

Set

Modifies specific settings of an object

Get

Queries a specific object or a subset of a type of object, such as a specified mailbox or all mailbox users

You can work with cmdlets in several ways:

  • Executing commands directly at the shell prompt

  • Running commands from scripts

  • Calling them from C# or other .NET Framework languages

You can enter any command or cmdlet you can run at the Windows PowerShell command prompt into a script by copying the related command text to a file and saving the file with the .ps1 extension. You can then run the script in the same way you would any other command or cmdlet.

Note

Windows PowerShell also includes a rich scripting language and allows the use of standard language constructs for looping, conditional execution, flow control, and variable assignment. Discussion of these features is beyond the scope of this book. A good resource is Windows PowerShell 2.0 Administrator’s Pocket Consultant (Microsoft Press, 2009).

From the Windows command-line environment or a batch script, you can execute Windows PowerShell cmdlets with the -Command parameter. Typically, when you do this, you also want to suppress the Windows PowerShell logo and stop execution of profiles. After doing this, you can type the following command at a command prompt or insert it into a .BAT script:

powershell -nologo -noprofile -command get-service

Finally, when you are working with Windows PowerShell, the current directory is not part of the environment path in most instances. Because of this, you typically need to use “./” when you run a script in the current directory, such as:

./runtasks

Running and using other commands and utilities

Because Windows PowerShell runs within the context of the Windows command prompt, you can run all Windows command-line commands, utilities, and graphical applications from within Windows PowerShell. However, remember that the Windows PowerShell interpreter parses all commands before passing off the command to the command prompt environment. If Windows PowerShell has a like-named command or a like-named alias for a command, this command, and not the expected Windows command, is executed. (See the Using cmdlet aliases section later in this chapter for more information on aliases.)

Non–Windows PowerShell commands and programs must reside in a directory that is part of the PATH environment variable. If the item is found in the path, it is run. The PATH variable also controls where the Windows PowerShell looks for applications, utilities, and scripts. In Windows PowerShell, you can work with Windows environment variables using $env. To view the current settings for the PATH environment variable, type $env:path. To add a directory to this variable, use the following syntax:

$env:path += ";DirectoryPathToAdd"

where DirectoryPathToAdd is the directory path you want to add to the path, such as:

$env:path += ";C:Scripts"

To have this directory added to the path every time you start Windows PowerShell, you can add the command line as an entry in your profile. Profiles store frequently used elements, including aliases and functions. Generally speaking, profiles are always loaded when you work with Windows PowerShell. Keep in mind that cmdlets are like built-in commands rather than standalone executables. Because of this, they are not affected by the PATH environment variable.

Working with cmdlets

Cmdlets provide the basic foundation for working with a computer from within the Windows PowerShell. Although there are many different cmdlets with many different available uses, cmdlets all have common features, which I’ll examine in this section.

Using Windows PowerShell cmdlets

At the Windows PowerShell prompt, you can get a complete list of cmdlets available by typing get-command. However, the output lists both cmdlets and functions by name and definition. For cmdlets, the definition provided is the syntax, but the full syntax rarely fits on the line. A better way to get information about cmdlets is to use Get-Help.

If you type get-help *-*, you get a list of all cmdlets, including a synopsis that summarizes the purpose of the cmdlet—which is much more useful than a list of commands. To get help documentation on a specific cmdlet, type get-help followed by the cmdlet name, such as:

get-help get-variable

Windows PowerShell uses online and updatable help files. Because of this, you may see only basic syntax for cmdlets and functions. To get full help details, you’ll have to either use online help or download the help files to your computer. For online help, add the -online option to your get-help command, such as:

get-help get-variable -online

Use the Update-Help cmdlet to download and install the current help files from the Internet. Without parameters, Update-Help updates the help files for all modules installed on the computer. However, Update-Help:

  • Downloads files only once a day

  • Installs files only when they are newer than the ones on the computer

  • Limits the total size of uncompressed help files to 1 GB

You can override these restrictions using the -Force parameter. Table 4-2 provides a list of cmdlets you’ll commonly use for administration. Although many other cmdlets are available, these are the ones you’re likely to use the most.

Table 4-2. Cmdlets commonly used for administration

CMDLET NAME

DESCRIPTION

Add-Computer, Remove-Computer, Stop-Computer, Restart-Computer

Adds or removes domain membership or stops or restarts a computer

Add-JobTrigger, Get-JobTrigger, New-JobTrigger, Set-JobTrigger

Cmdlets for adding, getting, creating, and setting triggers for scheduled jobs.

Checkpoint-Computer, Restore-Computer

Creates a system restore checkpoint for a computer, or restores a computer from a checkpoint

Compare-Object, Group-Object, Sort-Object, Select-Object, New-Object

Cmdlets for comparing, grouping, sorting, selecting, and creating objects

Connect-PSSession, Disconnect-PSSession

Connects or disconnects of PowerShell remote session.

ConvertFrom-SecureString, ConvertTo-SecureString

Cmdlets for creating or exporting secure strings

Get-Alias, New-Alias, Set-Alias, Export-Alias, Import-Alias

Cmdlets for getting, creating, setting, exporting, and importing aliases

Get-AuthenticodeSignature, Set-AuthenticodeSignature

Cmdlets for getting or setting the signature object associated with a file

Get-Command, Invoke-Command, Measure-Command, Trace-Command

Cmdlets for getting information about cmdlets, invoking commands, measuring the run time of commands, and tracing commands

Get-Counter

Gets performance counter data

Get-Credential

Gets a credential object based on a password

Get-Date, Set-Date

Gets or sets the current date and time

Get-EventLog, Write-EventLog, Clear-EventLog

Gets events, writes events, or clears events in an event log

Get-ExecutionPolicy, Set-ExecutionPolicy

Gets or sets the effective execution policy for the current shell

Get-Host

Gets information about the PowerShell host application

Get-HotFix

Gets the Quick Fix Engineering (QFE) updates that have been applied to a computer

Get-Location, Set-Location

Displays or sets the current working location

Get-Process, Start-Process, Stop-Process

Gets, starts, or stops processes on a computer

Get-PSDrive, New-PSDrive, Remove-PSDrive

Gets, creates, or removes a specified PowerShell drive

Get-ScheduledJob, Disable-ScheduledJob, Enable-ScheduledJob, Set-ScheduledJob

Cmdlets for getting, disabling, enabling, and setting scheduled jobs

Get-Service, New-Service, Set-Service

Gets, creates, or sets system services

Get-Variable, New-Variable, Set-Variable, Remove-Variable, Clear-Variable

Cmdlets for getting, creating, setting, and removing variables as well as for clearing variable values

Import-Counter, Export-Counter

Imports or exports performance counter log files

New-EventLog, Remove-EventLog, Limit-EventLog

Creates or removes a custom event log and event source, or sets the size and age limits for an event log

Read-Host, Write-Host, Clear-Host

Reads input from, writes output to, or clears the host window

Reset-ComputerMachinePassword

Changes and resets the machine account password that the computer uses to authenticate in a domain

Show-EventLog

Displays a computer’s event logs in Event Viewer

Start-Sleep

Suspends shell or script activity for the specified period

Stop-Service, Start-Service, Suspend-Service, Resume-Service, Restart-Service

Cmdlets for stopping, starting, suspending, resuming, and restarting system services

Wait-Process

Waits for a process to be stopped before accepting input

Write-Output

Writes an object to the pipeline

Write-Warning

Displays a warning message

Using cmdlet parameters

All cmdlet parameters are designated with an initial dash (-). To reduce the amount of typing required, some parameters are position-sensitive, so you can sometimes pass parameters in a specific order without having to specify the parameter name. For example, with Get-Service, you don’t have to specify the -Name parameter, you can simply type:

get-service ServiceName

where ServiceName is the name of the service you want to examine, such as:

get-service MSExchangeIS

This command line returns the status of the Microsoft Exchange Information Store service. Because you can use wildcards, such as *, with name values, you can also type get-service mse* to return the status of all Microsoft Exchange–related services.

All cmdlets support the common set of parameters listed in Table 4-3. However, to use these parameters, you must run the cmdlet in such a way that these parameters are returned as part of the result set.

Table 4-3. Common cmdlet parameters

PARAMETER NAME

DESCRIPTION

Confirm

Pauses processes and requires the user to acknowledge the action before continuing. Cmdlets beginning with Remove and Disable have this parameter.

Debug

Provides programming-level debugging information about the operation.

ErrorAction

Controls the command behavior when an error occurs.

ErrorVariable

Sets the name of the variable (in addition to the standard error) in which to place objects for which an error has occurred.

OutBuffer

Sets the output buffer for the cmdlet.

OutVariable

Sets the name of the variable in which to place output objects.

Verbose

Provides detailed information about the operation.

WarningAction

Determines how a cmdlet responds to a warning message. Valid values are SilentlyContinue (suppress the warning and continue), Continue (display the warning and continue), Inquire (display the warning and prompt to confirm before continuing), and Stop (display the warning and halt execution). The default value is Continue.

WarningVariable

Sets the name of the variable (in addition to the standard error) in which to store warnings that have occurred.

WhatIf

Allows the user to view what would happen if a cmdlet were run with a specific set of parameters. Cmdlets beginning with Remove and Disable have this parameter.

Understanding cmdlet errors

When you work with cmdlets, you’ll encounter two standard types of errors:

  • Terminating errors. Errors that halt execution

  • Nonterminating errors. Errors that cause error output to be returned but do not halt execution

With both types of errors, you’ll typically see error text that can help you resolve the problem that caused it. For example, an expected file might be missing or you might not have sufficient permissions to perform a specified task.

Using cmdlet aliases

For ease of use, Windows PowerShell lets you create aliases for cmdlets. An alias is an abbreviation for a cmdlet that acts as a shortcut for executing the cmdlet. For example, you can use the alias gsv instead of the cmdlet name Get-Service.

Table 4-4 provides a list of commonly used default aliases. Although there are many other aliases, these are the ones you’ll use most frequently.

Table 4-4. Commonly used cmdlet aliases

ALIAS

CMDLET

clear, cls

Clear-Host

Diff

Compare-Object

cp, copy

Copy-Item

Epal

Export-Alias

Epcsv

Export-Csv

Foreach

ForEach-Object

Fl

Format-List

Ft

Format-Table

Fw

Format-Wide

Gal

Get-Alias

ls, dir

Get-ChildItem

Gcm

Get-Command

cat, type

Get-Content

h, history

Get-History

gl, pwd

Get-Location

gps, ps

Get-Process

Gsv

Get-Service

Gv

Get-Variable

Group

Group-Object

Ipal

Import-Alias

Ipcsv

Import-Csv

R

Invoke-History

Ni

New-Item

Mount

New-PSDrive

Nv

New-Variable

rd, rm, rmdir, del, erase

Remove-Item

Rv

Remove-Variable

Sal

Set-Alias

sl, cd, chdir

Set-Location

sv, set

Set-Variable

Sort

Sort-Object

Sasv

Start-Service

Sleep

Start-Sleep

spps, kill

Stop-Process

Spsv

Stop-Service

write, echo

Write-Output

You can define additional aliases using the Set-Alias cmdlet. The syntax is:

set-alias aliasName cmdletName

where aliasName is the alias you want to use and cmdletName is the cmdlet for which you are creating an alias. The following example creates a “go” alias for the Get-Process cmdlet:

set-alias go get-process

To use your custom aliases whenever you work with Windows PowerShell, enter the related command line in your profile.

Working with Exchange Management Shell

Exchange Management Shell is a command-line management interface built on Windows PowerShell. You use Exchange Management Shell to manage any aspect of an Exchange Server 2013 configuration that you can manage in Exchange Admin Center. This means that you can typically use either tool to configure Exchange Server 2013. However, only Exchange Management Shell has the full complement of available commands, and this means that some tasks can be performed only at the shell prompt.

Running and using Exchange Management Shell

After you’ve installed the Exchange management tools on a computer, you can start to use Exchange Management Shell and the following techniques:

  • With Windows 8 or later and Windows Server 2012 or later, you can start Exchange Management Shell by using the Apps Search box. Type shell in the Apps Search box, and then select Exchange Management Shell. Or tap or click Start and then choose Exchange Management Shell.

  • With Windows 7 and Windows Server 2008 R2, you can start Exchange Management Shell by clicking Start, pointing to All Programs, clicking Microsoft Exchange Server 2013, and then clicking Exchange Management Shell.

Exchange Management Shell is designed to be run only on domain-joined computers. Whether you are logged on locally to an Exchange server or working remotely, this opens a custom Windows PowerShell console. The console does the following:

  1. Connects to the closest Exchange 2013 server using Windows Remote Management (WinRM).

  2. Performs authentication checks that validate your access to the Exchange 2013 server and determine the Exchange role groups and roles your account is a member of. You must be a member of at least one management role.

  3. Creates a remote session with the Exchange 2013 server. A remote session is a runspace that establishes a common working environment for executing commands on remote computers.

Selecting the shell in this way starts Exchange Management Shell using your user credentials. This enables you to perform any administrative tasks allowed for your user account and in accordance with the Exchange role groups and management roles you’re assigned. As a result, you don’t need to run Exchange Management Shell in elevated, administrator mode, but you can. To do so, press and hold or right-click Exchange Management Shell, and then tap or click Run As Administrator.

If you examine the properties of the shortcut that starts the Exchange Management Shell, you’ll see the actual command that runs when you start the shell is:

C:WindowsSystem32WindowsPowerShellv1.0powershell.exe -noexit -command
". 'C:Program FilesMicrosoftExchange ServerV15inRemoteExchange.ps1';
Connect-ExchangeServer -auto -ClientApplication:ManagementShell "

As you can see, the command starts PowerShell, runs the RemoteExchange.ps1 profile file, and then uses the command Connect-ExchangeServer to establish the remote session. Note the parameters passed in for Connect-ExchangeServer. The -ClientApplication parameter specifies that client-side application is Exchange Management Shell. The -Auto parameter tells the cmdlet to automatically discover and try to connect to an appropriate Exchange 2013 server. Discovery works like this:

  1. When you run the command on an Exchange 2013 server, the local server is tried first.

  2. Next, the command tries to connect to a Client Access server in the current Active Directory site.

  3. Finally, the command tries to connect to a Mailbox server in the current Active Directory site.

  4. If no server is available, the command exits.

The RemoteExchange.ps1 profile file sets aliases, initializes Exchange global variables, and loads .NET assemblies for Exchange. It also modifies the standard PowerShell prompt so that it is scoped to the entire Active Directory forest and defines the following Exchange-specific functions:

  • Functions. Allows you to list all available functions by typing functions.

  • Get-Exbanner. Displays the Exchange Management Shell startup banner whenever you type get-exbanner.

  • Get-Exblog. Opens Internet Explorer and accesses the Exchange blog at Microsoft whenever you type get-exblog.

  • Get-Excommand. Allows you to list all available Exchange commands by typing get-excommand.

  • Get-Pscommand. Allows you to list all available PowerShell commands by typing get-pscommand.

  • Get-Tip. Displays the tip of the day whenever you type get-tip.

  • Quickref. Opens Internet Explorer and allows you to download the Exchange Management Shell quick start guide whenever you type quickref.

The RemoteExchange.ps1 profile loads the ConnectFunctions.ps1 script, which defines a number of functions that enable AutoDiscover and Connect features. The functions include the following:

  • Connect-ExchangeServer

  • CreateOrGetExchangeSession

  • Discover-EcpVirtualDirectoryForEmc

  • Discover-ExchangeServer

  • _AutoDiscoverAndConnect

  • _CheckServicesStarted

  • _ConnectToAnyServer

  • _GetCAFEServers

  • _GetCASServers

  • _GetCurrentVersionServers

  • _GetExchangeServersInSite

  • _GetHostFqdn

  • _GetHubMailboxUMServers

  • _GetLocalForest

  • _GetServerFqdnFromNetworkAddress

  • _GetSites

  • _GetWebServiceServers

  • _GetURL

  • _NewExchangeRunSpace

  • _OpenExchangeRunSpace

  • _PrintUsageAndQuit

  • _SelectVdir

These functions are available for you to use whenever you work with Exchange Management Shell or have loaded the ConnectFunctions.ps1 script. However, only Connect-ExchangeServer, CreateOrGetExchangeSession, Discover-EcpVirtualDirectoryForEmc and Discover-ExchangeServer are meant to be called directly. The other functions are helper functions.

When you are working with Exchange Management Shell or have run ConnectFunctions.ps1, you can view the source for a function by typing functions followed by the name of the function, such as functions connect-exchangeserver.

If you want to access Exchange features from a manual remote shell (as discussed later in this chapter under “Using a manual remote shell to work with Exchange”) or within scripts, you need to load the RemoteExchange.ps1 profile file. You can find an example of the command required to do this by viewing the properties of the shortcut for Exchange Management Shell. In the Properties dialog box, the Target text is selected by default. Press Ctrl+C to copy this text so that you can use it. For example, if you copy the Target text and paste it into an elevated command prompt (cmd.exe), you can access Exchange Management Shell and work with Exchange Server. If you copy the Target text and paste it into a script, you can be sure that the manual remote session is established when you run the script.

You also can customize the way Exchange Management Shell is initialized by editing the shortcut properties or by copying the shortcut that starts Exchange Management Shell and then editing the properties. With Windows 8 or later and Windows Server 2012 or later, one way to create a new shortcut for Exchange Management Shell is to do the following:

  1. If an Exchange Management Shell shortcut is not pinned to the desktop taskbar, open the Start screen. Next, right-click Exchange Management Shell and then select Pin To Taskbar.

  2. On the desktop, right-click the taskbar shortcut for Exchange Management Shell. This displays the Tasks dialog box.

  3. In the Tasks dialog box, right-click Exchange Management Shell and then select Properties. This opens the Properties dialog box for the shortcut with the Shortcut tab selected.

  4. Click in the Target box. The text should be selected automatically so you can copy it in the next step. If the text isn’t selected, press Ctrl+A to select all of the related text.

  5. Press Ctrl+C to copy the selected text and then click OK to close the Properties dialog box.

  6. Right-click an open area of the desktop, select New, and then select Shortcut. This opens the Create Shortcut dialog box.

  7. In the Create Shortcut dialog box, click in the Type The Location Of The Item box and then press Ctrl+V to paste the previously selected text.

  8. Click Next. Type a name for the shortcut, such as Custom EMC. Click Finish to create the shortcut.

  9. Run the shortcut with your custom options by double-clicking it on the desktop.

An extra command must always be added to the Target text. This additional command is Connect-ExchangeServer, a command enabled when the ConnectFunctions.ps1 script runs. To customize the initialization of remote sessions, other parameters are available:

  • -ClearCache. A troubleshooting option that allows you to clear registry entries and exported modules and then re-create the registry settings and import modules. After you clear the cache, you can try to connect again using options you need.

    connect-exchangeserver -clearcache
  • -Forest. Allows you to specify a single part name or the fully qualified domain name (FQDN) of the Active Directory forest in which to perform discovery. You must be able to authenticate in the forest. User credentials you provide for the -Username parameter are not used for discovery. Use with -Auto.

    connect-exchangeserver -auto -forest ForestName
  • -Prompt Prompts you for the FQDN of the Exchange server to connect to. If you use -Prompt with -Auto, you are prompted only if PowerShell cannot connect automatically. If you use -Prompt with -ServerFqdn, you are prompted only if PowerShell cannot connect to the specified server.

    connect-exchangeserver -auto -prompt
  • -ServerFqdn. Allows you to specify the FQDN of the Exchange server to connect to.

    connect-exchangeserver -serverfqdn ExServerFQDN
  • -Username Allows you to specify the user name to use for authentication. You will be prompted for the user’s password. You can also pass in a Credential object. Use with -ServerFqdn or -Auto.

    connect-exchangeserver -serverfqdn ExServerFQDN
    -username UserName

    Real World

    When you are working with some cmdlets and objects in PowerShell, you might need to specify a credential for authentication. To do this, use Get-Credential to obtain a Credential object and save the result in a variable for later use. Consider the following example:

    $cred = get-credential

    PowerShell reads this command, prompts you for a user name and password, and then stores the credentials provided in the $cred variable. You also can specify that you want the credentials for a specific user in a specific domain. The following example requests the credentials for the ExAdmin account in the Pocket-Consultant.com domain:

    $cred = get-credential -credential pocket-consultaexadmin

    A Credential object has UserName and Password properties that you can work with. Although the user name is stored as a regular string, the password is stored as a secure, encrypted string. Simply pass in the credential instead of the user name as shown in this example:

    $cred = get-credential -credential pocket-consultaexadmin
    get-hotfix -credential $cred -computername mailserver18

Important

When you prompt for credentials, integrated Windows authentication is used for authentication. However, if the credentials are not set when prompted, such as when the user selects Cancel, Kerberos authentication is used with the user’s default credentials.

Real World

Where a domain name is required for credentials, you typically can use either the NET BIOS domain name or the DNS domain name. In the previous examples, I entered the NET BIOS domain name pocket-consulta rather than the DNS name pocket-consultant.com.

When you call Connect-ExchangeServer, the function does one of two things: It opens a remote session by using implicit credentials (the credentials of the user who is running Exchange Management Shell) or by using specified credentials (credentials you’ve explicitly provided). One of the final things Connect-ExchangeServer does is call _OpenExchangeRunSpace, which in turn calls _NewExchangeRunspace to establish the remote session.

In the script, the core code for _OpenExchangeRunSpace is:

$global:remoteSession = _NewExchangeRunspace $fqdn $credential $UseWIA
$SuppressError $ClientApplication $AllowRedirection

And the core code for _NewExchangeRunspace is:

$so = New-PSSessionOption -OperationTimeout $sessionOptionsTimeout
-IdleTimeout $sessionOptionsTimeout -OpenTimeout $sessionOptionsTimeout;
New-PSSession -ConnectionURI "$connectionUri" -ConfigurationName
Microsoft.Exchange -SessionOption $so

The code sample creates a global variable named $remoteSession to hold the remote session. A global variable is used to ensure that the session remains active and available when the script exits. The session is established using New-PSSession with a connection URI for a particular Exchange server. For example, if the Exchange server’s FQDN is MailServer15.Cpandl.com, the connection URI is https://mailserver15.cpandl.com/powershell. The -ConfigurationName parameter sets the configuration namespace as Microsoft.Exchange (in place of the default Microsoft.PowerShell). The -SessionOption parameter sets session options that were defined previously using the New-PSSessionOption cmdlet. The session options include the operation timeout value, the idle timeout value, and the open session timeout value. By default, all three are set to 180,000 milliseconds (180 seconds) via the $sessionOptionsTimeout variable defined in the first section of the ConnectFunctions.ps1 script.

You can use the MsExchEmsTimeout environment variable to set the default timeout values. If you set this environment variable to a value of 900,000 milliseconds or less (15 minutes or less), the timeouts are set accordingly. If you set this environment variable to a value greater than 900,000 milliseconds, the timeout values revert to the 3-minute default value.

Real World

When you connect to Exchange Admin Center in a browser, the browser version determines your experience level, and the location of your mailbox determines whether you see the console for Exchange 2007, Exchange 2010, or Exchange 2013. This is not the case when you are working with the shell. With the shell, the experience level is always set to FULL. Further, the HKLM:SOFTWAREMicrosoftExchangeServerv15Setup key in the registry is examined to determine the Exchange version and the build number, and then this information is used to set the client version compatibility level. Thus, a precise connection URI is set as http://$fqdn/powershell?serializationLevel=Full;ExchClientVer=$clientVersion.

Managing the PowerShell application

Microsoft Internet Information Services (IIS) handles every incoming request to a website within the context of a web application. A web application is a software program that delivers web content to users over HTTP or HTTPS. Each website has a default web application and one or more additional web applications associated with it. The default web application handles incoming requests that aren’t assigned to other web applications. Additional web applications handle incoming requests that specifically reference a particular application.

When you connect to a server using a URL, such as https://mailserver15.cpandl.com/powershell, you are performing remote operations via the PowerShell application running on the web server providing Exchange services. Like all web applications, the PowerShell application has a virtual directory associated with it. The virtual directory sets the application name and maps the application to the physical directory that contains the application’s content.

You can manage the PowerShell application using IIS Manager GUI and Exchange Management Shell. The related commands for Exchange Management Shell are:

  • Get-PowerShellVirtualDirectory. Displays information about the PowerShell application running on the web server providing services for Exchange.

    Get-PowerShellVirtualDirectory [-Identity 'AppName']
    [-DomainController 'DomainControllerName']
    Get-PowerShellVirtualDirectory -Server 'ExchangeServerName'
    [-DomainController 'DomainControllerName']
  • New-PowerShellVirtualDirectoryCreates a new PowerShell application running on the web server providing services for Exchange.

    New-PowerShellVirtualDirectory -Name 'AppName'
    [-AppPoolId 'AppPoolName'] [-BasicAuthentication <$true | $false>]
    [-CertificateAuthentication <$true | $false>] [-DomainController
    'DomainControllerName'] [-ExternalUrl 'URL'] [-InternalUrl 'URL']
    [-Path 'PhysicalDirectoryPath']
    [-WindowsAuthentication <$true | $false>]
  • Remove-PowerShellVirtualDirectory. Removes a specified PowerShell application running on the web server providing services for Exchange.

    Remove-PowerShellVirtualDirectory -Identity 'AppName'
    [-DomainController 'DomainControllerName']
  • Set-PowerShellVirtualDirectory. Modifies the configuration settings for a specified PowerShell application running on the web server providing services for Exchange.

    Set-PowerShellVirtualDirectory -Identity 'AppName'
    [-BasicAuthentication <$true | $false>] [-CertificateAuthentication
    <$true | $false>] [-DomainController 'DomainControllerName']
    [-ExternalUrl 'URL'] [-InternalUrl 'URL']
    [-LiveIdBasicAuthentication <$true | $false>]
    [-WindowsAuthentication <$true | $false>]

At the Exchange Management Shell prompt, you can confirm the location of the PowerShell application by typing get-powershellvirtualdirectory.

GetPowerShellVirtualDirectory lists the name of the application, the associated directory and website, and the server on which the application is running, as shown in the following example:

Name                             Server
-------                          -------
PowerShell (Default Web Site)    CorpServer45

In this example, a standard configuration is being used where the application named PowerShell is running on Default Web Site on CorpServer45. You can use Set-PowerShellVirtualDirectory to specify the internal and external URL to use as well as the permitted authentication types. Authentication types you can enable or disable include basic authentication, Windows authentication, certificate authentication, and Live ID basic authentication. You can use New-PowerShellVirtualDirectory to create a new PowerShell application on the web server providing services for Exchange and Remove-PowerShellVirtualDirectory to remove a PowerShell application.

Real World

Any change you make to the PowerShell virtual directory configuration requires careful pre-planning. For every potential change, you’ll need to determine whether you need to modify the WinRM configuration and the PowerShell path in ConnectFunctions.ps1 scripts on management computers and Exchange servers, as well as the specific changes you’ll need to make with regard to IIS on your Client Access servers.

Microsoft cautions against modifying the default configuration for the PowerShell virtual directory because any mistakes you make could prevent you from managing Exchange Server. Because Exchange configuration data is stored in Active Directory and the affected IIS metabase, you would need to be able to restore Exchange data in Active Directory and the affected IIS metabase to a previous state to recover.

Customizing Exchange Management Shell

Now that you know how the Exchange Management Shell environment works, you can more easily customize the shell to work the way you want it to. One way to do this is to modify the menu shortcut that starts Exchange Management Shell or create copies of this menu shortcut to change the way Exchange Management Shell starts. For example, if you want to connect to a named Exchange server rather than any available Exchange server, you can do the following:

  1. In the Properties dialog box for the shortcut that starts Exchange Management Shell, the Target text is selected by default. Press the right arrow key to move to the end of the command text.

  2. Delete -Auto and type -ServerFqdn followed by the FQDN of the Exchange server, such as -ServerFQDN MailServer12.Cpandl.com. Tap or click OK.

That said, this entire sequence of tasks is meant to simplify the task of establishing an interactive remote session with a single Exchange server. As implemented in the default configuration, you have a one-to-one, interactive approach for remote management, meaning you establish a session with a specific remote server and work with that specific server simply by executing commands.

When you are working with PowerShell outside of Exchange Management Shell, you might want to use the Enter-PSSession cmdlet to start an interactive session with an Exchange server or any other remote computer. The basic syntax is Enter-PSSession ComputerName, where ComputerName is the name of the remote computer, such as the following:

enter-pssession mailserver15

After you enter this command, the command prompt changes to show that you are connected to the remote computer, as shown in the following example:

[MailServer15]: PS C:Userswrstanek.cpandlDocuments>

Now, the commands that you type run on the remote computer just as if you had typed them directly on the remote computer. In most cases, you need to ensure you are running an elevated, administrator shell and that you pass credentials along in the session. When you connect to a server in this way, you use the standard PowerShell remoting configuration and do not go through the PowerShell application running on a web server. You can end the interactive session by using the command Exit-PSSession or typing exit.

To access an Exchange server in the same way as the ConnectFunctions.ps1 script, you need to use the -ConnectionURI parameter to specify the connection URI, the -ConfigurationName parameter to specify the configuration namespace, the -Authentication parameter to set the authentication type to use, and optionally, the -SessionOption parameter to set session options. Consider the following example:

enter-pssession -connectionURI http://mailserver12.cpandl.com/powershell
-ConfigurationName Microsoft.Exchange -Authentication Kerberos

Here, you set the connection URI as https://mailserver12.cpandl.com/powershell, set the configuration namespace as Microsoft.Exchange, and use Kerberos authentication with the implicit credentials of your user account. If you don’t specify the authentication method, the default authentication method for WinRM is used. If you want to use alternate credentials, you can pass in credentials as shown in this example:

$cred = get-credential -credential pocket-consultawilliams
enter-pssession -connectionURI https://mailserver12.cpandl.com/powershell
-ConfigurationName Microsoft.Exchange -credential $cred
-Authentication Kerberos

Here, you set the connection URI as https://mailserver12.cpandl.com/powershell, set the configuration namespace as Microsoft.Exchange, and use alternate credentials. When PowerShell reads the Get-Credential command, you are prompted for the password for the specified account. Because the authentication type is not defined, the session uses the default authentication method for WinRM.

To put this all together, one way to create a script that runs on an Exchange server is to run the RemoteExchange.ps1 profile file and then run the ConnectFunctions.ps1 script to autoconnect to Exchange. The commands you insert into your script to do this are the following:

$s = $env:ExchangeInstallPath + "binRemoteExchange.ps1"
&$s
$t = $env:ExchangeInstallPath + "binConnectFunctions.ps1"
&$t

Here, you define variables that point to the RemoteExchange.ps1 and ConnectFunctions scripts in the Exchange installation path, and then you use the & operator to invoke the scripts. The environment variable ExchangeInstallPath stores the location of the Exchange installation. If you enter the full path to a script, you don’t need to assign the path to a variable and then invoke it. However, you then have a fixed path and might need to edit the path on a particular Exchange server. Be sure to run the script at an elevated, administrator PowerShell prompt.

To create a script that runs on your management computer and then executes commands remotely on an Exchange server, insert commands in your script to create a new session and then invoke commands in the session using the techniques discussed in the next section.

Performing one-to-many remote management

PowerShell also lets you perform one-to-many remote management. To do so, you must work with an elevated, administrator shell and can either invoke remote commands on multiple computers or establish remote sessions with multiple computers. When you remotely invoke commands, PowerShell runs the commands on the remote computers, returns all output from the commands, and establishes connections to the remote computers only for as long as is required to return the output. When you establish remote sessions, you can create persistent connections to the remote computers and then execute commands within the session. Any command you enter while working in the session is executed on all computers to which you are connected, whether this is one computer, ten computers, or a hundred computers.

Tip

As discussed in Chapter 1 WinRM must be appropriately configured on any computer you want to remotely manage. Although WinRM is configured on Exchange servers and most others computers running Windows 8 or later and Windows Server 2012 or later, WinRM listeners generally are not created by default. You can create the required listeners by running winrm quickconfig.

The following command entered as a single line invokes the Get-Service and Get-Process commands on the named servers:

invoke-command -computername MailServer12, MailServer21, MailServer32
-scriptblock {get-service; get-process}

The following command establishes a remote session with the named computers:

$s = new-PSSession -computername MailServer12, MailServer21, MailServer32
-Credential CpandlWilliamS

When you connect to a server in this way, you use the standard PowerShell remoting configuration and are not going through the PowerShell application running on a web server. After you establish the session, you can then use the $s session with Invoke-Command to return commands on all remote computers you are connected to. This example looks for stopped Exchange services on each computer:

invoke-command -session $s
-scriptblock {get-service mse* | where { $_.status -eq "stopped"}}

In this example, you pipe the output of Get-Service to the Where-Object cmdlet and filter based on the Status property. Because the $_ automatic variable operates on the current object in the pipeline, PowerShell examines the status of each service in turn and lists only those that are stopped in the output.

In addition to working with remote commands and remote sessions, some cmdlets have a ComputerName parameter that lets you work with a remote computer without using Windows PowerShell remoting. PowerShell supports remote background jobs as well. A background job is a command that you run asynchronously in an interactive or noninteractive session. When you start a background job, the command prompt returns immediately, and you can continue working while the job runs. For a complete discussion of these remoting features, see Chapter 4, “Using Sessions, Jobs, and Remoting” in Windows PowerShell 2.0 Administrator’s Pocket Consultant (Microsoft Press, 2009).

Troubleshooting Exchange Management Shell

Note that the ConnectionFunctions.ps1 script relies on your organization having a standard Exchange Server configuration. By default, Exchange is configured for management using HTTP with the URL http://ServerName/powershell. If you’ve modified the Web Server configuration on your Exchange servers to use a different path, such as might be required to enhance security, you need to update the connection URIs used in the ConnectionFunctions.ps1 script.

When you invoke the PowerShell application, the web server to which you connect runs the PowerShell plug-in (Pwrshplugin.dll) and the Exchange Authorization plug-in (Microsoft.Exchange.AuthorizationPlugin.dll). The PowerShell plug-in runs as a Microsoft.Exchange shell and has the following initialization parameters:

  • PSVersion, which sets the PowerShell version as 3.0

  • ApplicationBase, which sets the base path for the Exchange server as %ExchangeInstallPath%Bin

  • AssemblyName, which sets the name of the .NET assembly to load as Microsoft.Exchange.Configuration.ObjectModel.dll

The Authorization plug-in handles Exchange authorization and authentication. Together, these plug-ins create an authorized shell environment for the remote session.

The physical directory for the PowerShell application is %ExchangeInstallPath%ClientAccessPowerShell. This application runs in the context of an application pool named MSExchangePowerShellAppPool. In a large organization, you might want to optimize settings for this and other application pools, as discussed in Chapter 9, “Managing Applications, Application Pools, and Worker Processes,” in Internet Information Services (IIS) 7.0 Administrator’s Pocket Consultant (Microsoft, 2007).

In the %ExchangeInstallPath%ClientAccessPowerShell directory on your server, you’ll find a web.config file that defines the settings for the PowerShell application. This file contains a role-based access control (RBAC) configuration section that loads the assemblies and web controls for the application.

Tip

Microsoft recommends against changing the PowerShell application configuration. However, there’s nothing magical or mystical about the PowerShell application or MSExchangePowerShellAppPool. You can re-create these features to enable remote management in alternate configurations, such as on nondefault websites or websites with alternate names. However, be sure to copy the PowerShell application’s web.config file to the physical directory for your base application. Before you make any changes to a live production environment, you should plan and test your changes in a nonproduction test environment.

The Web server to which you connect processes your remote actions via the Exchange Control Panel (ECP) application running on the default website. With Exchange 2013, you see the ECP as Exchange Admin Center. The physical directory for this application is %ExchangeInstallPath%ClientAccessEcp. This application runs in the context of an application pool named MSExchangeECPAppPool.

In the %ExchangeInstallPath%ClientAccessECP directory on your server, you’ll find a web.config file that defines the settings for the ECP application. This file contains an RBAC configuration section that loads the assemblies and web controls for the application.

Because of the interdependencies created by accessing Exchange via web applications, you’ll want to examine related features as part of troubleshooting any issues you experience with remote sessions. Generally, your troubleshooting should follow these steps:

  1. Examine the status and configuration of the WinRM on your local computer and the target Exchange server. The service must be started and responding.

  2. Check the settings of any firewall running on your local computer, the target Exchange server, or any device between the two, such as a router with a firewall.

  3. Check the status of the World Wide Web Publishing Service on the Exchange server. The service must be started and responding.

  4. Check the configuration settings of the PowerShell and ECP applications on the web server. By default, the applications don’t have access restrictions, but another administrator could have set restrictions.

  5. Check the status of MSExchangePowerShellAppPool and MSExchangeECPAppPool. You might want to recycle the application pools to stop and then start them.

  6. Check the configuration settings of MSExchangePowerShellAppPool and MSExchangeECPAppPool. By default, the application pools are configured to use only one worker process to service requests.

  7. Check to ensure the PowerShell application’s web.config file is present in the physical directory for the application, and also that the file has the appropriate settings.

  8. Check to ensure the ECP application’s web.config file is present in the physical directory for the application and also that the file has the appropriate settings.

Working with Exchange cmdlets

When you are working with Exchange Management Shell, additional Exchange-specific cmdlets are available. As with Windows PowerShell cmdlets, you can get help information on Exchange cmdlets:

  • To view a list of all Exchange cmdlets, type get-excommand at the shell prompt.

  • To view Exchange cmdlets related to a specific server role, type get-help -role RoleName, where RoleName is the name of the server role you want to examine. You can use the following role names:

    • *UM* for cmdlets related to the Unified Messaging server role

    • *Mailbox* for cmdlets related to the Mailbox server role

    • *ClientAccess* for cmdlets related to the Client Access server role

When you work with Exchange Management Shell, you’ll often work with Get, Set, Enable, Disable, New, and Remove cmdlets (the groups of cmdlets that begin with these verbs). These cmdlets all accept the -Identity parameter, which identifies the unique object with which you are working.

Typically, a cmdlet that accepts the -Identity parameter has this parameter as its first parameter, allowing you to specify the identity, with or without the parameter name. When identities have names as well as aliases, you can specify either value as the identity. For example, you can use any of the following techniques to retrieve the mailbox object for the user William Stanek with the mail alias Williams:

get-mailbox -identity williams
get-mailbox -identity 'William Stanek'
get-mailbox Williams
get-mailbox "William Stanek"

With Get cmdlets, you typically can return an object set containing all related items simply by omitting the identity. For example, if you type get-mailbox at the shell prompt without specifying an identity, you get a list of all mailboxes in the enterprise (up to the maximum permitted to return in a single object set).

By default, all cmdlets return data in table format. Because there are often many more columns of data than fit across the screen, you might need to switch to Format-List output to see all of the data. To change to the Format-List output, redirect the output using the pipe symbol (|) to the Format-List cmdlet, as shown in this example:

get-mailbox -identity williams | format-list

You can abbreviate Format-List as fl, as in this example:

get-mailbox -identity williams | fl

Either technique typically ensures that you see much more information about the object or the result set than if you were retrieving table-formatted data.

Working with object sets and redirecting output

When you are working with PowerShell or Exchange Management Shell, you’ll often need to redirect the output of one cmdlet and pass it as input to another cmdlet. You can do this using the pipe symbol. For example, if you want to view mailboxes for a specific mailbox database rather than all mailboxes in the enterprise, you can pipe the output of Get-MailboxDatabase to Get-Mailbox, as shown in this example:

get-mailboxdatabase -Identity "Engineering" | get-mailbox

Here, you use Get-MailboxDatabase to get the mailbox database object for the Engineering database. You then send this object to the Get-Mailbox cmdlet as input, and Get-Mailbox iterates through all the mailboxes in this database. If you don’t perform any other manipulation, the mailboxes for this database are listed as output, as shown here:

Name              Alias           Server       ProhibitSendQuota
Administrator     Administrator   corpsvr127   unlimited
William S         williams        corpsvr127   unlimited
Tom G             tomg            corpsvr127   unlimited
David W           davidw          corpsvr127   unlimited
Kari F            karif           corpsvr127   unlimited
Connie V          conniev         corpsvr127   unlimited
Mike D            miked           corpsvr127   unlimited

You can also pipe this output to another cmdlet to perform an action on each individual mailbox in this database. If you don’t know the name of the mailbox database you want to work with, enter get-mailboxdatabase without any parameters to list all available mailbox databases.

Using a manual remote shell to work with Exchange

Although the easiest way to work remotely with Exchange 2013 is to install the management tools on your computer, you can connect to and manage Exchange 2013 if you don’t have the management tools installed. To do this, you can use a manual remote shell to connect to an Exchange 2013 server. However, you lose the benefits of the preconfigured tools which set up the environment and manage the Exchange connection for you. You also can use a manual remote shell to connect to and work with Exchange Online.

Preparing to use the remote shell

As you might expect, there are several prerequisites for creating a manual remote shell. The computer you use to connect an Exchange server must be running one of the following operating systems:

  • Windows Server 2012 RTM or R2

  • Windows Server 2008 R2 SP1

  • Windows 8 or later

  • Windows 7 SP1

The computer must have Windows Management Framework, which includes Windows PowerShell and WinRM, and Microsoft .NET Framework 4.5. Although Windows Server 2012 RTM or R2 and Windows 8 or later include these components, Windows 7 SP1 and Windows Server 2008 R2 SP1 do not.

Real World

When you install the Client Access server role for Exchange 2013, the server is configured automatically with a Windows PowerShell gateway that is configured as a proxy service. This proxy service allows you to run remote commands in web browsers and in remote sessions. Whenever you work with Exchange Admin Center or Exchange Management Shell, the commands are executed via this proxy—even if you logged on locally.

Before you can work remotely, WinRM must be running and the authentication mechanisms you want to use must be enabled. Because Exchange Online uses Basic authentication, you may need to enable this. At an elevated, administrator PowerShell prompt, enter the following commands to check the status of WinRM:

get-service "winrm"

If WinRM isn’t running, start the service by entering:

start-service "winrm"

Next, ensure that the authentication mechanisms you want to use are enabled for use with WinRM. To do this, enter the following command:

winrm get winrm/config/client/auth

Although you are working in the PowerShell window, this command is passed through to the command prompt and the output states the status of available authentication mechanisms:

Auth
    Basic = false
    Digest = true
    Kerberos = true
    Negotiate = true
    Certificate = true
    CredSSP = false

If Basic authentication isn’t enabled and you want to work with Exchange Online, you must enable it. Unfortunately, there’s no easy way to pass a complex command through to the command prompt. Because of this, you’ll need to open an elevated command prompt and then enter the following command:

winrm set winrm/config/client/auth '@{Basic="true"}'

Important

Exchange Management Shell and Exchange Admin Center require integrated Windows authentication. Exchange Online uses Basic authentication.

Once you’ve ensured WinRM is running and configured appropriately, you can check the status of script execution by entering the following command at the PowerShell prompt:

Get-ExecutionPolicy

Windows PowerShell script execution must be enabled on your computer. Typically, you’ll want to use the RemoteSigned execution policy. If so, enter the following command at an elevated, administrator PowerShell prompt:

Set-ExecutionPolicy RemoteSigned

When you connect to a remote Exchange server, you can use your current network credentials or you can specify another set of credentials. Either way, the user account that you want to use for remote management must be a member of a management role group or be enabled for remote shell.

By default, when you create a new mailbox user for Exchange 2013 or Exchange Online, the mailbox user has remote PowerShell enabled. You can view the access status for all users in the Exchange organization by entering the following command:

Get-User -ResultSize unlimited |
Format-Table Name,DisplayName,RemotePowerShellEnabled

If you want to display a list of only users who don’t have access, you could filter the results for this value by running the following command instead:

Get-User -ResultSize unlimited -Filter {RemotePowerShellEnabled -eq $false}

Set the filtered value to $true if you want to see a list of only users who have access. You can check the access status of a specific user as well by specifying the SAM account name, display name, or login name of the user, as shown in these examples:

Get-User "williams" | Format-List RemotePowerShellEnabled
Get-User "William Stanek" | Format-List RemotePowerShellEnabled
Get-User "[email protected]" | Format-List
RemotePowerShellEnabled

Connecting manually to Exchange 2013 servers

In an elevated, administrator Windows PowerShell window, you can establish a connection to the remote Exchange server using a PowerShell session. When your management computer is joined to the domain, you can use either HTTP or HTTPS with Kerberos authentication to establish the session. However, HTTPS is normally disabled by default in the client configuration. The basic syntax is:

$Session = New-PSSession -ConfigurationName Microsoft.Exchange
-ConnectionUri http://Exchange2013CASName/PowerShell/
-Authentication Kerberos

where Exchange2013CASName is the host name or FQDN of the Exchange 2013 Client Access server to which you want to connect and PowerShell is the name of the PowerShell virtual directory on the server, such as:

$Session = New-PSSession -ConfigurationName Microsoft.Exchange
-ConnectionUri http://mailserver35.pocket-consultant.com/PowerShell/
-Authentication Kerberos

With Kerberos authentication, your current credentials are used to establish the session. Keep in mind that with Kerberos authentication you must use the server name or the FQDN and cannot use an IP address.

If you want to use an authentication mechanism other than Kerberos or your computer isn’t connected to a domain, you must use HTTPS as the transport (or the destination server must be added to the TrustedHosts configuration settings for WinRM, and HTTP must be enabled in the client configuration). You also must explicitly pass in a credential using the -Credential parameter.

You also can specify the authentication mechanism, such as Basic, Digest, or Negotiate. All communications are encrypted with HTTPS. The modified syntax is then:

$Session = New-PSSession -ConfigurationName Microsoft.Exchange
-ConnectionUri https://Exchange2013CASNameOrIP/PowerShell/
-Authentication Negotiate -Credential Credential

where Exchange2013CASNameOrIP is the FQDN or IP address of the Exchange 2013 Client Access server to which you want to connect, PowerShell is the name of the PowerShell virtual directory on the server, and Credential sets the user name under which the session is established. Consider the following example:

$Session = New-PSSession -ConfigurationName Microsoft.Exchange
-ConnectionUri https://mailserver35.pocket-consultant.com/PowerShell/
-Authentication Negotiate -Credential pocket-consultawilliams

Here, you establish a session with MailServer35 using integrated Windows authentication and store this session in the $Session object. As you are passing in a credential for Williams, you are prompted for and must enter the account password. You also can store the credential in a Credential object and then use Get-Credential to request the credentials. The syntax then becomes:

$Cred = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange
-ConnectionUri https://mailserver35.pocket-consultant.com/PowerShell/
-Authentication Negotiate -Credential $Cred

Important

Regardless of whether you use Kerberos or another authentication mechanism, the Exchange server’s SSL certificate must contain a common name (CN) that matches the identifier you are using. Otherwise, you won’t be able to connect.

Connecting manually to Exchange Online

Connecting manually to Exchange Online is similar to connecting manually to on-premises servers running Exchange 2013. In an elevated, administrator Windows PowerShell window, you can establish a connection to Exchange Online using a PowerShell session. You can use a stand-alone computer or a domain-joined computer that meets the requirements discussed earlier under “Preparing to use the remote shell.”

The basic syntax for connecting manually to Exchange Online is:

$Cred = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange
-ConnectionUri https://ps.outlook.com/powershell/
-Authentication Basic -Credential $Cred -AllowRedirection

Here, you use HTTPS with Basic authentication for the session and establish a connection to the Exchange Online URL provided by Microsoft, which typically is https://ps.outlook.com. To establish the connection, you must pass in your Exchange Online user name and password. This example stores credentials in a Credential object and then uses Get-Credential to prompt for the required credentials. You also could specify the credentials explicitly, as shown here:

$Session = New-PSSession -ConfigurationName Microsoft.Exchange
-ConnectionUri https://ps.outlook.com/powershell/
-Authentication Basic -Credential [email protected]
-AllowRedirection

Here, you are prompted for the password for the account.

Note

When you work with Exchange Online, keep in mind that not all of the cmdlets are available as compared to an on-premises installation. This is because the operating environments are different. Exchange Online runs on Windows Azure. You can connect to and work directly with the Microsoft Online service and Windows Azure as discussed in the section of Chapter 6 titled “Understanding on-premises and online recipient management.”

Managing remote sessions

After you establish a session with an Exchange 2013 server or Exchange Online, you must import the server-side PowerShell session into your client-side session by running the following command:

Import-PSSession $Session

You can then work with the remote server.

When you are finished, you should disconnect the remote shell from Exchange server. It’s important to note that, beginning with Windows PowerShell 3.0, sessions are persistent by default. When you disconnect from a session, any command or scripts that are running in the session continue running, and you can later reconnect to the session to pick up where you left off. You also can reconnect to a session if you were disconnected unintentionally, such as by a temporary network outage.

Important

With Exchange Online, each account can have only three connections to sever-side sessions at a time. If you close the PowerShell window without disconnecting from the session, the connection remains open for 15 minutes and then disconnects.

To disconnect a session without stopping commands or releasing resources, run the following command:

Disconnect-PSSession $Session

The $Session object was instantiated when you created the session. As long as you don’t exit the PowerShell window in which this object was created, you can use this object to reconnect to the session by entering:

Connect-PSSession $Session

When you are completely finished with the session, you should remove it. Removing a session stops any commands or scripts that are running, ends the session, and releases the resources the session was using. Remove a session by running the following command:

Remove-PSSession $Session
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset