Home Cloud & Networking Microsoft Exchange Server PowerShell Essentials

Microsoft Exchange Server PowerShell Essentials

By Biswanath Banerjee
books-svg-icon Book
eBook $29.99 $20.98
Print $38.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $29.99 $20.98
Print $38.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Getting Started with PowerShell
About this book
PowerShell has become one of the most important skills in an Exchange administrator's armory. PowerShell has proved its mettle so widely that, if you're not already starting to learn PowerShell, then you're falling behind the industry. It isn't difficult to learn PowerShell at all. In fact, if you've ever run commands from a CMD prompt, then you'll be able to start using PowerShell straightaway. This book will walk you through the essentials of PowerShell in Microsoft Exchange Server and make sure you understand its nitty gritty effectively. You will first walk through the core concepts of PowerShell and their applications. This book discusses ways to automate tasks and activities that are performed by Exchange administrators and that otherwise take a lot of manual effort. Microsoft Exchange PowerShell Essentials will provide all the required details for Active Directory, System, and Exchange administrators to help them understand Windows PowerShell and build the required scripts to manage the Exchange Infrastructure.
Publication date:
February 2016
Publisher
Packt
Pages
210
ISBN
9781782176039

 

Chapter 1. Getting Started with PowerShell

This chapter will provide introduction to Windows PowerShell that is required for the rest of the chapters of this book. You will learn about the usage of Windows PowerShell cmdlets, variables, arrays, and loops. You will also learn the use of the PowerShell Help system. We will cover the concept of filtering and exporting objects using pipelines and the usage of loops and conditional statements. This chapter will create a foundation, and we will use subsequent chapters to build this foundation.

The following topics will be discussed in this chapter:

  • Introducing Windows PowerShell

  • Understanding PowerShell syntax

  • Understanding the help system

  • Understanding logging and transcripts

  • Using variables

  • Using pipelines

  • Using looping

  • Using arrays

  • Using filters and exporting data

  • Using If statements

  • Writing a basic script

 

Introducing Windows PowerShell


Windows PowerShell is the evolution of the Windows command-line shell, which provides a scripting environment for MS-DOS and the Windows operating system. In MS-DOS and Windows 9X, the shell was command.com, and it was cmd.exe for Windows NT family of the operating system. In the UNIX world, there are different shells such as SH, KSH, CSH, and BASH.

Almost all of these shells provide an environment to execute a command or utility and present the output as text. These shells have some built-in commands such as dir in cmd.exe in Windows NT or later versions, but these built-in commands are limited; and hence, new utilities are written to fill the gap. Shells supported the use of a scripting language (batch files) to automate tasks. There were limitations when it came to creating complex scripts and automating all other aspects provided by a Graphical User Interface (GUI) as equivalent commands are not exposed and the scripting language was basic.

Windows scripting host (Wscript.exe) and its command-line counterpart called Cscript.exe was introduced in 1998 with the release of Windows 98 to address some of the challenges. It is a language-independent scripting environment and allows scripts written in Jscript and VBScript using the APIs exposed by applications. There were deficiencies in this scripting environment due to limited documentation and interoperability issues with shell and security vulnerabilities. There were several security breaches as computer viruses exploited features provided by WSH. There were a few other attempts made by Microsoft to build utilities for specific purpose—for example, netsh—with their list of supported command sets, but they were not integrated with the shell and were inoperable.

In 2005, Microsoft released a new shell called Monad (also known as Microsoft Shell(MSH)), which is designed to automate a wide range of administrative tasks and is based on a new design as opposed to its predecessors.

Similar to the command.com and cmd.exe shells, Windows PowerShell can run three types of programs: built-in commands, external programs, and scripts. However, unlike a command shell, the built-in commands are not embedded into the shell environment but are available as modules in one or more .DLL files. This allows both Microsoft and vendors to write custom modules to manage their applications using PowerShell. Now, most of Microsoft and vendor's applications support management through Windows PowerShell, for example, Windows Server, Exchange Server, SharePoint, Lync Server/Skype for business, and VMWare.

Windows PowerShell is different than its predecessors in the following ways:

  • Windows PowerShell processes objects instead of text that are based on the .Net framework and provide lots of built-in commands

  • All commands use the same command parser instead of different parser for each utility, which makes the use of PowerShell consistent and easier as compared to the earlier shell environments

  • Administrators can still use the tools and utilities that they are used to in Windows PowerShell such as Net, SC, and Reg.exe

  • As PowerShell is based on the .NET framework, one can write their own cmdlets using Microsoft Visual Studio and languages supported by the Common Language Runtime (CLR) such as C#

With the release of PowerShell 2.0, some APIs (application programming interface) were released that could be used to invoke PowerShell commands right from within your applications. Applications can then use certain PowerShell commands to perform a specific operation, which earlier could only be performed by GUI.

Starting from Exchange Server 2007, this capability has been used to its best advantage as will be explained over the course of the book. Learning PowerShell will help you in managing Microsoft, vendor applications, and services that support PowerShell. It will provide you the skillset required to manage and automate different aspects of Microsoft cloud-based offerings such as Office 365 and Windows Azure. Both of these support PowerShell and have specific modules for management. However, our focus in this book will be on managing Exchange through Windows PowerShell. At times, GUI is strictly used for illustration.

If you are interested in a .Net development, you can write your own cmdlet (pronounced as command-lets) in PowerShell that will perform a specific operation. For this, you will need PowerShell 2.0 Software Development Kit (SDK) and Visual Studio Express Edition. Both of these are free downloads.

Tip

You can download the example code files for this book 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.

The following table summarizes the history of the different versions of Windows PowerShell:

Version

Year released

Operating systems

Features

1

2006

Windows Server 2003, Windows Server 2008, Windows XP SP2, and Windows Vista

First release

2

2009

Windows XP SP3, Windows Server 2003 SP2, Windows Vista SP1, Windows Server 2008 R2, and Windows 7

Remoting, Eventing, jobs, modules, ISE, and Exception handling

3

2012

Windows Server 2012 and Windows 8

Session connectivity, Scheduled jobs, update-help, and resumable sessions

4

2013

Windows Server 2012 R2, Windows 8.1, Windows 7 SP1, Windows Server 2008 R2 SP1, and Windows Server 2012

Desired State Configuration, Enhanced debugging, exportable help, and network diagnostics

5.0

2015

In Public Preview at the time of writing this book

OneGet, PowerShellGet, class definitions, and switch management improvements

 

Understanding PowerShell syntax


Windows PowerShell uses a verb-noun pair as a naming system. The name of each cmdlet includes a standard verb hyphenated with a specific noun. Verbs are used for specific actions in Windows PowerShell, and nouns are used to describe objects by users and system administrators. Here are some of the examples that show how little effort is required to work with cmdlets, and one does not have to memorize them.

Nouns in a cmdlet describe what the cmdlet will act on. For example, get-process, get-service, stop-process and stop-service. If this is used regularly, one can get to know the standard set of verbs and nouns used in PowerShell. With these verb-noun pair, hundreds of cmdlet names can be remembered and used.

You will be able to recognize the operation performed by a cmdlet by just reading the name as it is mostly apparent about the name used by a new command should relate to the operation. For example, get-computer will give you a list of computers on your network. Get-date and get-time will display the system date and time respectively. Similarly, stop-computer will shut down a computer. Set-date and set-time will set the system's date and time.

Let's look at how to list all the commands that have the particular verbs called Get and Set using Get-command with the –verb parameter. The output of this command is piped to display in a table format (more on this will be covered later in the Usage of pipelines section).

In the next example, we will just use instead of a format table:

Now, let's use the -Noun parameter, and we will find a list of commands that affect the same object type. For example, if you want to see commands that are available for managing computers, type the following command:

Traditionally, the commands in the earlier shells usually do not have a consistent parameter name. Sometimes, they don't have a name at all, and even if they do, they are abbreviated to make typing easier. But, this makes it difficult for new users to understand the parameters that are used. In Windows PowerShell, consistency is encouraged by using developer guidance on the usage of parameter names.

The names of the parameters in Windows PowerShell have a hyphen '-' prepended to them to allow PowerShell to demarcate them as parameters. In the get-command –Noun example, the name of the parameter is Noun and is typed as –Noun.

The cmdlets in Windows PowerShell support several common parameters as the PowerShell engine controls these parameters. So, no matter how they are implemented, they will behave in a similar way. Another way to drive the consistency and learning of Windows PowerShell are some of the common parameters like—Confirm, WhatIf, outvariable, warningaction, warningvariable, debug, and verbose.

 

Understanding the help system


This section will cover the use of help in Windows PowerShell. The help topic for a particular command or conceptual help can assist an administrator who is new to Windows PowerShell or using a particular set of cmdlets to understand its syntax and usage.

The Help parameter (?)

The -? parameter with a cmdlet will display Windows PowerShell help for the cmdlet:

The Get-Help cmdlet

The Get-Help cmdlet displays help information about PowerShell cmdlets. Some of the examples are discussed as follows.

The following example gives you the help files from the PowerShell help system one page at a time:

PS C:\>get-help * | more

If you know the alias of the cmdlet you are trying to get help for, use the —detailed parameter for full help:

PS C:\>get-help gps -detailed

If you are not sure of the exact parameter but remember the initial letter, use the following to get help:

PS C:\>get-help get-process -parameter i*

This lists all the parameters of the cmdlet get-process:

PS C:\>get-help get-process -Parameter *

This provides help with the syntax of the select-object cmdlet:

PS C:\>(get-help select-object).syntax

There are other properties of the help object such as input types, module name, examples, and more. If you are looking to find all the properties and methods of help object type called get-help <cmdlet-name> | get-member, for example, PS C:\> get-help get-Service | get-member.

 

Understanding Logging and Transcripts


The transcript feature in PowerShell helps you to record all your cmdlets and activities at the prompt. This feature is not available for use in the PowerShell application during the writing of this book. This will help you capture all the commands and outputs from the commands that appear in the console in a text file that you specify using the start-transcript cmdlet.

The Start-transcript cmdlet initializes a transcript file, and then creates records of all the subsequent actions in the PowerShell session.

The syntax is shown as follows:

Here are some of the important parameters that you should know about the start-transcript cmdlet. To save the transcript file to a specified path, use the –Path parameter. You cannot use wildcards when you set the path, but you can also use variables. The directories in the path must exist or the command will fail.

The default behavior of the Start-Transcript cmdlet is to overwrite any file that is in the transcript path unless the –noClobber parameter is specified, which prevents Windows PowerShell from overwriting an existing file.

The –Append parameter will add the new transcript to the end of an existing file. For example, take a look at the following:

PS C:\> Start-Transcript -Path C:\transcript\transcript01.txt –NoClobber

When you want to stop recording the transcript, you can either exit the console or type Stop-transcript. The Stop-Transcript cmdlet requires no additional parameters.

The Stop-transcript cmdlet stops recording actions that was started by the start-transcript cmdlet. Use the following syntax:

PS C:\> stop-transcript
 

Using variables


In PowerShell, the data is stored, retrieved, and modified using the methods listed next. In this section, we are going to cover only variables:

  • A variable is used to store bits of information

  • Arrays are used to store information in an index

  • A Hash table uses key-value pair to store data

A variable is virtual storage to store information that will be utilized later in a script or the information that is the output of running a script. Variables can contain different data types such as text strings, objects, and integers. There are few special variables that you can use, which are defined in PowerShell.

The examples of some of the special variables are as follows:

Special Variable

Description

$_

This is the same as the $PS item. It contains the current object in the pipeline object and can be used in commands that perform an action on all or selected objects in a pipeline.

$Home

This contains the path of the user's' home directory, typically C:\Users\<UserName>.

$Error

This is an array that contains the errors in the current execution. The first element in the array ($Error[0]) will contain the most recent error.

$NULL

This is an automatic variable that contains a NULL or empty value.

If you are looking for a full list of automatic variables available for use in Windows PowerShell, type the following:

PS C:\> get-help about_automatic_variables

In PowerShell, all the variable names must start with the $ character. Data is assigned to a variable using the = operator:

PS C:\> $Number = 25

There are the Set-Variable and Get-Variable cmdlets that can also be used to set and retrieve the values of the variable.

Here, the value 401B is passed to the variable ExamCode:

PS C:\> Set-Variable -Name ExamCode -Value 401B
PS C:\> Get-Variable ExamCode

A little bit about operators that are used for assignment and comparison of values assigned to variables.

Assignment operators

The following operators are used to assign values to variables and carry out numeric operations before the assignment:

Operator

Description

=

A specific value is assigned to a variable using the equal to = operator

+=

The variable value is increased by a specific number

-=

The variable value is decreased by the number specified

*=

This operator is used to multiply the value stored in a variable by a specified number

/=

This divides the value by a specific number

%=

In this case, the value stored in the variable is divided by the specified number and the modulus (remainder) is stored in the variable

++

This increases the value of variables by 1

--

This decreases the value of variables by 1

The example assigns the value of to the variable called $Book:

$Bookk = "Microsoft Exchange PowerShell Essentials"

In the previous example, the $Book variable is created as we have assigned the value to the variable using the assignment operator. If you look at the following example, the first statement creates a $x variable and assigns a value of 12. The second statement has changed its value to 34:

$x = 12
$ = 34

While scripting, there is a need to combine operations such as addition, subtraction, and assignment to variables. For example, the following statements will produce the exact same output:

$i += 3
$i = ($i +3)

Similarly, if you want to multiply first and then assign, use any of the following statements:

$n *= 4
$n = ($n * 4)

If you want to use a specific data type, you have to override how PowerShell stores values in variables. This can be achieved by strongly typed variables or casting them. For example, the first one is a variable that will only store integers and the second one will store strings:

[int]$Number = 12
[string]$Book = "Microsoft Exchange PowerShell Essentials"

Now, let's take a look at an example of what happens if we do not specify the correct datatype to a variable. Here, we have stored the value of 56 in the $x variable as a string. The next statement adds the value of 8 to the variable. The output will be displayed as a string and numeric operation will be performed. As a best practice, you should always cast your variables with the correct data type:

[string]$s =  56
$s += 8
$s
568

You will not be able to recast a variable without changing its value. In our previous example, we have casted $Book as a string value and stored the value of Microsoft Exchange PowerShell Essentials in it. If you try to use the following statement, you will get an error message, which essentially means that you have to change the value before you cast the variable to a different data type:

[int]$Book 

Cannot convert value string to type System.Int32. Error—"Input string was not in a correct format."

At line:1 char:1
+ [int]$b 
+ ~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvalidCastFromStringToInteger

Now, let's use the Windows PowerShell help system to learn more about other assignment operators:

PS C:\> get-help about_assignment_operators

Comparison operators

These operators are used to compare values and match specific patterns. Here is the list of comparison operators available, and these operators are case insensitive. If you want to make these operators case sensitive or insensitive, precede c or i in front of the following operator:

  • eq

  • -ne

  • -gt

  • -ge

  • -lt

  • -le

  • -Like

  • -NotLike

  • -Match

  • -NotMatch

  • -Contains

  • -NotContains

  • -In

  • -NotIn

  • -Replace

Take a look at the following examples:

-eq—Equal to:

PS C:\> "apple" -eq "apple"
True
PS C:\> "apple" -eq "orange"
False

-ne—Not Equal to:

PS C:\> "apple" -ne "apple"
False
PS C:\> "apple" -ne "orange"
True

-gt—Greater than:

PS C:\> 5 -gt 8
False
PS C:\> 23,34,56 -gt 50
56

Like—Match using the wildcard character (*).

Take a look at the following examples:

PS C:\> "Windows PowerShell" -like "*shell"
True
PS C:\> "Windows PowerShell", "Server" -like "*shell"
          Windows PowerShell

Review the help for other comparison operators:

PS C:\> get-help about_comparison_operators
 

Using pipelines


A pipeline is a series of cmdlet statements connected through the pipeline (|) character (ASCII 124). Pipelines are used to send the output objects from one command as an input to another command. This can be used in scripts and console to build complex statements.

The output of Get-Service is piped to more command that displays information one screen at a time:

Get-Servince | more

You can use pipelines to build complex queries. For example, the following example will get the output of the Get-Service cmdlet and pipe it to the Where-Object cmdlet that will filter the services whose names match the MSExchange text, and the status is set to Running. The logical and operator is used in this case to combine the two conditions:

Get-Service | Where-Object {($_.Name –like "MSExchange*") –and ($_.Status –eq "Running")}

So far, we saw how to take output from one command and feed it into the next one. Now, let's take it further by adding one more piping. The following statement will get the output of the Get-Service cmdlet and pass it to Where-object where it will filter it for Exchange services, which are stopped, and then it will pass the output using another pipeline to Start-Service cmdlet. So, using this one-line command, you can check which Exchange Services are not running and start them. We have used the—autosize parameter to format the output based on the number of columns and their sizes:

Get-Service | Where-Object {($_.Name –like "MSExchange*") –and ($_.Status –eq "Stopped")} | Start-Service
 

Using loops


In this section, we will review the usage of loops in Windows PowerShell. Every scripting language has multiple ways to loop through an array of items and execute a block of statements. Windows PowerShell has a variety of looping mechanisms described next.

The Do loop

Here is another way to run a statement block based on a conditional result. The Do loop is used with While and Until keywords to run a script block along with a conditional statement. Both the loop Do-While and Do-Until run once before the condition is evaluated. The command block is executed in a Do-While loop as long as the condition is true, whereas a Do-Until loop runs until a condition evaluates to be true.

The syntax of Do-While and Do-Until is the same. The following shows the syntax of the Do-While statement:

          do {<command block>} while (<condition>)
          do {<command block>} until (<condition>)

Examples are as follows:

Count to 5—In the following example, the statement is to use an increment operator with a $a variable and increment the value by 1 (as listed earlier in the assignment operators section of this chapter), and the condition is evaluated to be true until the value of a is less than 5. Here is how we will use the loop in a single line in PowerShell:

PS C:\> Do { $a++ ; Write-Host $a } while($a -ne 5)

The previous statement can be used in a different way where a carriage return is used instead of a semi-colon:

 PS C:\>  Do { $a++ 
          Write-Host $a
        } while($a -ne 5) 

The Do-Until loop executes the statement list until the condition is false. Once the condition evaluates to be true, the loop exits.

In the following example, the script block will write the output of the variable to the console and increment it by 1, and the process is repeated until the condition, which is the value, becomes greater than 5 is evaluated to be false. Once $Count exceeds number 5, changing the condition to true, the loop exits:

PS C:\>  $Count = 1
do {Write-Host $Count; $Count++}
until ($Count -gt 5)

ForEach loops

The ForEach statement is used to iterate through a series of items in a collection. A typical collection is to traverse through the items in an array. You can specify within the ForEach loop a command or a command block against each item in the array:

Syntax is as follows:

                     foreach ($<Element> in $< group of items>){Command Block>}

The following ForEach loop displays the values of the $Number array.

In Windows PowerShell, the entire ForEach statement should be in one line for execution. Here is an example:

$Numbers = "1","2","3","4","5"; foreach ($No in $Numbers) {Write-Host $No}

If you are using a PowerShell script file, you can use the ForEach statement using multiple lines in a .ps1 file:

  $Numbers = "1","2","3","4","5"
  foreach ($No in $Numbers)
  {
  Write-Host $No
  }

In the previous example, the $Numbers array is used to store values from 1 to 5. The ForEach statement loops through each of the items in the $Number array. In the first time, it sets the $No variable with value 1, second time with value 2, and so on. The loops exit when the value of 5 is reached.

We will use ForEach in the remaining chapters with cmdlets that return a collection. For example, we will use ForEach to iterate through each of the file/directory returned by Get-ChildItem in this case:

foreach ($item in Get-ChildItem)
        {
              Write-Host $item
        }

Loop through an array of strings:

 $Fruit = @("Apple","Peach","Banana","Strawberry") foreach ($fruit in $fruit) { "$fruit = " + $fruit.length }
The following example displays all the numbers in the series except 2:
foreach ($num in 1,2,3,4,5) { if ($num -eq 2) { continue } ; $num }

While loops

The While loop is used to execute statements in the command block as long as the condition is evaluated to be true.

Here is the syntax of a While loop:

while (<condition to be evaluated>) {<Command Block>}

In a while statement, the condition is evaluated to be either true or false. As long as the condition is true, the command block is executed, which can be a combination of more commands running through each iteration of the loop.

The following example lists numbers from 1 to 9 as the value of variable is $value is evaluated to be true until its value is equal to 9:

  while ($value -ne 9)
  {
  $value++
  Write-Host $value
  }

You can write the same command in PowerShell in one line as follows:

while($value -ne 9){$value++; Write-Host $value}

Note that there is a semi-colon (;) that separates the two commands in the command block. The first one increments the value of $value by 1, and the second command writes the output of $value to the console.

 

Using arrays


An array is a variable that stores multiple items that are either of the same or different data type. An array can be created by assigning multiple values to a variable separated by a comma. The operator is used to assign values is the assignment operator (=). The following example creates an array that contains numbers 34, 56, 2, 23, and 8:

$Array = 34, 56, 2, 23, 8

A range operator (..) can also be used to create and initialize an array. The following example will create an array that will store the numbers from 1 to 5:

$Number = 1..5

This will store the values 1, 2, 3, 4, and 5 into the $Number.

If you do not specify the data type during creation, PowerShell creates an array of type:System.Object[]. You can use the GetType() method to display the type of array object created. For instance, the data type of the $Number array will be listed by:

$Number.GetType().

If you need an array that can have items of a particular data type, use the strongly typed array by preceding the array variable name with the data type such as the following example where $intarray contains 32-bit integer values:

[int32[]]$intarray = 1000, 2000, 3000, 4000

This will result in $intarray containing only integers as we have specified that no values other than int32 data type is allowed as value in this array.

In Windows Powershell, you can create arrays consisting of any supported data type in the Microsoft .Net framework.

Now, let's take an example of an array with multiple data types:

$mixedArray = 6,"Hello",4.5,"World"

The array subexpression operator is used to create an array with zero or more objects. Use the following syntax for the operator @( ... ):

$mixedArray = @(6,"Hello",4.5,"World")

Some other examples are as follows:

The following example creates an empty array:

$EmptyArray = @()

Create an array with a single element:

$Array = @("Hello World")

Create a multidimensional array:

$MultiDimArray = @(
             (4,5,6),
             (24,30,36)
   )

Retrieving values from an array

If you type the array name, it will display all the items in that array:

$Array

The array number index starts at 0, so the first element will be accessed by this:

$Array[0]  

This is similar to displaying the fifth element in the $Array use:

$Array[4]

The last element of the array will be displayed by -1. So, the following example displays the last four items:

$Array[-4..-1]

We have used the range operator (..) here, which can also be used to display the elements from values 1 to 5 in the next example:

$Array[1..5]

The (+) operator combines the elements of the array. Use the following example to display the elements at index 0, 1, 3, and 5 to 8:

$Array[0,1,3+5..8]

The length property of the Count alias will display the number of items in an array:

 $Array.Count

While, ForEach, and For looping statements are used to display items in an array:

Foreach ($item in $Array) {$item}

The following For statement loops through and displays every third item in the array:

For ($n = 0; $n –le ($Array.length -1); $n+=3) {$Array[$n]}

The While statement is used to list the items in an array until the defined condition becomes false. The following example displays the items until the index position is less than 6:

$i=0
while($i -lt 5) {$a[$i]; $i++}

Now, let's look at manipulating items in arrays. The replacement of an item in an array can be done by using the assignment (=) operator and the index of the present item to be replaced. The following example replaces the fourth element with the value of 23:

$Array[3] = 23 

The SetValue method can also be used to replace the value of items in an array. The following example replaces the third value (index position 2) with a value of 34:

$Array.SetValue(34,2)

The elements are added to the array by the use of the += operator. The following example adds an element of 250 to the $Array array:

$Array +=250

The default array class in PowerShell does not provide an easy way to delete the elements of the array. Array elements can be copied over to another array and old arrays can be deleted though. In the following example, the $x array will consist of all the items from $array except the third and fifth items:

$x = $array[0,1,3 + 5..($array.length - 1)]

Multiple arrays can be combined in a single array by using a plus operator (+). The following example creates three arrays $a, $b, and $c and combines them to $x, which will now have all the elements of the three arrays:

        $a = 2,4,6,8,10
        $b = 1,3,5,7,9
        $c = 11,12,13,14,15
        $x= $a+$b+$c

Arrays can be deleted by assigning the value of $null to the array; for example, $array = $null.

For additional help on arrays, use the following cmdlet:

PS C:\> get-help about_arrays
 

Using filters and exporting data


In order to understand how powerful Windows PowerShell is, you need to look at the filtering capabilities it offers. With an understanding of objects and pipelining, you can retrieve the exact information you are looking for. The Usage of Pipeline section talks about how pipelines can be used to pass one or more objects, which are the output of one command, and feed them into another cmdlet. In Windows PowerShell, there are commands that will help you to refine and get the desired output. Some of these cmdlets that we will look in this section are Where-Object, Sort-Object, Select-Object, and Select-String.

The Where-Object cmdlet helps you to filter the output returned by other cmdlets. For example, the Get-service cmdlet without any parameter retrieves information about the services installed on the computer on which it is called:

Now, let's filter the output of Get-Service to find the list of services that are stopped:

Windows PowerShell supports the following logical operators that we are going to use in our next example of filtering the output of a Get-Service cmdlet:

Operator

Description

-and

This is true only when both statements are true

-or

This is true when either or both statements are true

-xor

This is true if one condition is true and the other one is false

-not

The statement followed by this operator is negated

!

This is the same as the –not operator

We will now find services that are running whose name starts with Windows using the –and operator:

By default, Windows PowerShell will sort the output of commands using an alphabetical order. You can then use the Sort-object cmdlet to sort it using any way you like. For example, the following example will first sort the output of the Get-Process cmdlet by the Process ID and then the CPU time:

At times, you might need to filter your results based on certain specific property names. This is where the Select-Object cmdlet comes in handy. It selects the stated properties of a single or group of objects. You can use Select-Object to select objects that are unique in a group of objects It supports parameters such as First, Last, Skip, and Index. You can select one or multiple object properties using the –Property parameter. Let's take an example of the output of the Get-Process cmdlet, and let's say you are troubleshooting a performance issue on a server and are only interested to know about the CPU time and process name properties. The output of the Get-Process cmdlet will be piped to Select-Object with the –property parameter set to the process name and CPU. The Format-list cmdlet will format the output displayed in the console:

PS C:\> Get-Process | Select-Object -Property Processname, CPU | format-list

Now, let's use another parameter called –Unique of Select-Object. This will select a single member from a number or objects with same properties and values. In the following example, you will notice that the –Unique parameter is case sensitive and reports "c" and "C" as unique.

Another useful filtering cmdlet is Select-String, used to select text patterns in strings and files. If you are familiar with UNIX shells, it is used as Grep or Findstr in Windows. It can display all the matches or stop after the first match depending on the usage of the cmdlet. You can search files of Unicode text using this command as well.

First, we will create a file using the redirection operator (>) to store the list of services running on a server to a text file:

PS C:\> Get-Service > service.txt

Now, we will find the text "Network" and "Windows" to get a list of all the services that have the word in it. We will then use the –notmatch parameter to list all the services except this word:

Note that the search performed here is a case insensitive search; you can use the —case sensitive parameter to make it case sensitive, which means you won't get any output if you use the parameter with the previous command as there are no matches found.

 

Using If statements


In this section, we will use the if conditional statement If to execute statements based on a specific condition test to be true. We can also use the If command to do tests on more than one condition or even if all the other conditions are evaluated to be false.

The following example shows the If statement syntax:

        if (<Condition1>) 
                {<Command Block 1>}
        [elseif (<Condition2>)
                {<Command Block 2>}]
        [else
                {<Command Block 3>}]

We will use the if command to check the status of the services running on the computer, and if the status is stopped, it will be displayed in red and the running services will be displayed in green. We will use a combination of pipeline, the foreach-object cmdlet, and the if statement.

PS C:\> get-service | foreach-object {if ($_.status -eq "stopped") {write-host -foregroundcolor red $_.Displayname}` else {write-host -foregroundcolor green $_.Displayname }} 

Let's take a look at another example where you would like to find whether a particular folder is created. We will use a Test-Path cmdlet, which will return true if it finds the folder and false if it does not. As I am using the statement on my Active Directory domain controller, the folder is not present under Program Files, and this is what you will see in the output:

PS C:\> $ExchangeFolder = "C:\Program Files\Microsoft\Exchange Server"
PS C:\> $FolderPresent = Test-Path $ExchangeFolder
PS C:\> if ($FolderPresent -eq $True) {Write-Host "Exchange installation Folder found on this Server"} else {Write-Host "Exchange installation folder not present"}
Exchange installation folder not present
 

Switch statements


A Switch statement is used to check multiple conditions. It is equivalent to a series of If statements. The Switch statement lists each condition and an optional action. If a condition is true, the action is performed:

Syntax:

        Switch (<test-value>)
        {
            <condition> {<action>}
            <condition> {<action>}
        }

The Switch statement compares the value of 2 to each of the conditions listed. Once the test value matches the condition, the action is performed:

        PS> switch (2) 
         {
            1 {"It is one."}
            2 {"It is two."}
            3 {"It is three."}
            4 {"It is four."}
         } 
        It is two.

In the previous example, the value is compared to each condition in the list and there is a match for the value of 2. Let's take a look at the same example where we have added another condition that matches the value of 2:

        PS> switch (2) 
         {
            1 {"It is one."}
            2 {"It is two."}
            3 {"It is three."}
            4 {"It is four."}
            2 {"Two again."}
         } 
        It is two.
        Two again.

Using the Break statement, you can directly switch to stop the comparison after a match and terminate the switch statement:

        PS> switch (2) 
         {
            1 {"It is one."}
            2 {"It is two."; Break}
            3 {"It is three."}
            4 {"It is four."}
            2 {"Two again."}
         } 
        It is two.
 

Writing a basic script


Now that we have covered the basics of Windows PowerShell, let's write our first script. PowerShell uses the .ps1 format to save scripts. Before we get into executing scripts, let's first understand the following PowerShell Script Execution Policies that are in place to prevent unwanted scripts from being executed on your computer.

The cmdlet Set-Execution Policy helps you to change the Policy of which scripts you can run on your computer. There are four different execution policies:

  • Restricted: In this mode, you cannot run any script and can use Windows PowerShell to run cmdlets in the interactive mode only.

  • AllSigned: Locally created and those signed by a trusted publisher can be run

  • RemoteSigned: Scripts downloaded from another computer can run only if these are signed by a trusted publisher

  • Unrestricted: All the scripts will run regardless of whether they are signed or not

Now, let's set the execution Policy to Remote Signed and verify using Get-Execution Policy cmdlet:

PS C:\> Set-ExecutionPolicy RemoteSigned
PS C:\> Get-ExecutionPolicy

I am going to introduce the PowerShell Integrated Scripting Engine (ISE) that makes it easier to run scripts with features, such as syntax-coloring, tab completion, IntelliSense, visual debugging, and context sensitive Help, as compared to the PowerShell console.

The following script will query the win32_logical disk WMI class. This is a representation of a local storage device on a Windows Computer. There are six possible Drive Types, and we will use a Switch statement to get the output in text describing the type of storage:

 

Summary


In this chapter, you learned the usage of the cmdlet syntax in Windows PowerShell and the help system. We also covered variables and arrays used to store data. This data can then be exported and filtered in a lot of different ways by the use of operators, pipelines, and loops. Finally, the use of If statement is reviewed, which can be used to run a block of code based on a conditional test. These basics will be used throughout the rest of this book in examples and scripts.

In the next chapter, we are going to look at ways to manage recipients in an Exchange organization.

About the Author
  • Biswanath Banerjee

    Biswanath Banerjee has been working with Exchange Servers since 2005 in various roles in support, training, and consulting. Spanning an IT career of over 14 years, he has worked on multiple Active Directory and Exchange migration projects. He specializes in Planning and Deployment of Microsoft Infrastructure Solutions such as Active Directory, Exchange, Lync, Skype for Business, and various Office 365 services.

    Browse publications by this author
Latest Reviews (1 reviews total)
An excellent book for professionals. The price was attractive as well
Microsoft Exchange Server PowerShell Essentials
Unlock this book and the full library FREE for 7 days
Start now