Sei sulla pagina 1di 327

OFFICIAL MICROSOFT LEARNING PRODUCT

6434A
Automating Windows Server 2008 ®

Administration with Windows


PowerShell TM

Be sure to access the extended learning content on your


Course Companion CD enclosed on the back cover of the book.
Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, place or event is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part
of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted
in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for
any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.

The names of manufacturers, products, or URLs are provided for informational purposes only and
Microsoft makes no representations and warranties, either expressed, implied, or statutory,
regarding these manufacturers or the use of the products with any Microsoft technologies. The
inclusion of a manufacturer or product does not imply endorsement of Microsoft of the
manufacturer or product. Links may be provided to third party sites. Such sites are not under the
control of Microsoft and Microsoft is not responsible for the contents of any linked site or any link
contained in a linked site, or any changes or updates to such sites. Microsoft is not responsible for
webcasting or any other form of transmission received from any linked site. Microsoft is providing
these links to you only as a convenience, and the inclusion of any link does not imply endorsement
of Microsoft of the site or the products contained therein.
© 2008 Microsoft Corporation. All rights reserved.

Microsoft, and Windows are either registered trademarks or trademarks of Microsoft Corporation in
the United States and/or other countries.
All other trademarks are property of their respective owners.

Technical Reviewer: Trevor Barry

Product Number: 3639

Part Number (if applicable): 69118

Released: 07/1/2008
Contents
Module 1: Introduction to Windows PowerShell™
Lesson 1: Introduction to Windows PowerShell 1-3
Lesson 2: Installing Windows PowerShell in Windows Server 2008 1-10
Lab: Implementing Windows PowerShell 1-16

Module 2: Overview of Windows PowerShell™


Lesson 1: Overview of Objects 2-3
Lesson 2: Working with Cmdlets 2-9
Lesson 3: Tab Expansion, Aliases, and History 2-16
Lesson 4: Using Variables and Types 2-22
Lab: Working with Windows PowerShell Cmdlets, Aliases, Objects,
and Variables 2-28

Module 3 Building Pipelines for Assembly-Line Style Processing


Lesson 1: Using Pipelines 3-3
Lesson 2: Using Arrays 3-9
Lesson 3: Filtering and Iterating Through the Pipeline 3-15
Lesson 4: Reordering Objects in a Pipeline 3-21
Lab: Implementing Pipelines in Windows PowerShell 3-25

Module 4: Managing Processes and Formatting Cmdlet Output


Lesson 1: Managing Windows Processes with Windows PowerShell™ 4-3
Lesson 2: Formatting Cmdlet Output 4-9
Lab: Output Formatting and Process Control with Windows PowerShell 4-16
Module 5: Introduction to Scripting with Windows PowerShell™
Lesson 1: Writing Windows PowerShell Scripts 5-3
Lesson 2: Script Parameters 5-10
Lesson 3: Security in Windows PowerShell 5-16
Lesson 4: Customizing Windows PowerShell with Profiles 5-20
Lab: Implementing Scripts in Windows PowerShell 5-25

Module 6: Implementing Flow Control and Functions


Lesson 1: Controlling the Flow of Execution Within Scripts 6-3
Lesson 2: Iteration Flow Control 6-10
Lesson 3: Developing and Using Functions 6-15
Lab: Implementing Functions and Flow Control in Windows PowerShell 6-23

Module 7: Working with Files, the Registry, and Certificate Stores


Lesson 1: Using Data Stores 7-3
Lesson 2: Using Providers 7-10
Lesson 3: Filtering and Selecting with Regular Expressions 7-15
Lesson 4: Implementing Event Log Management 7-20
Lesson 5: Persisting Objects in Files 7-23
Lab: Working with Files, the Registry, and Certificate Stores 7-30

Module 8: Managing the Windows Operating System Using Windows


PowerShell and WMI
Lesson 1: Introduction to WMI and WMI Objects 8-3
Lesson 2: Managing Disks and Disk Volumes Using Windows PowerShell
with WMI 8-11
Lesson 3: Managing Shadow Copies Using Windows PowerShell with WMI 8-15
Lesson 4: Managing Shared Folders with Windows PowerShell 8-19
Lesson 5: Managing Terminal Services with WMI 8-22
Lesson 6: Managing IIS 7.0 with WMI 8-29
Lab: Managing the Windows Operating System with Windows PowerShell
and WMI 8-33

Module 9: Administering Microsoft® Active Directory® with Windows


PowerShell™
Lesson 1: Administering Domains and Forests Using .NET Objects 9-3
Lesson 2: Managing User Accounts and Groups Using ADSI 9-9
Lesson 3: Managing Relationships Between Users and Groups 9-17
Lesson 4: Web Administration Using IIS 7.0
Lab: Administering Active Directory with Windows PowerShell 9-27

Module 10: Administering Group Policy in Windows PowerShell™ Using COM


Lesson 1: Managing GPOs Using the GPMC COM Interface 10-3
Lesson 2: Managing Group Policy Settings 10-11
Lesson 3: Reporting Group Policy 10-15
Lab: Administering Group Policy in Windows PowerShell 10-18
Introduction to Windows PowerShell™ 1-1

Module 1
Introduction to Windows PowerShell™
Contents:
Lesson 1: Introduction to Windows PowerShell 1-3
Lesson 2: Installing Windows PowerShell in Windows Server 2008 1-10
Lab: Implementing Windows PowerShell 1-16
1-2 Introduction to Windows PowerShell™

Module Overview

Windows PowerShell is an interactive command shell and scripting environment


for administrative scripting. It is available for download for Windows® XP and
Windows Server® 2003, and is included as an optional feature in Windows Server
2008.
• As an interactive command shell, Windows PowerShell serves as a direct
administrator interface for managing Windows systems.
• As a scripting and administrative programming environment, Windows
PowerShell provides a platform for automating systems.

This module explains basic concepts in Windows PowerShell, including objects,


variables, cmdlets, and pipelines. It describes how to invoke available cmdlets and
aliases, as well as how to assign new aliases. The module also includes
demonstrations of tab expansion and basic operators.
Introduction to Windows PowerShell™ 1-3

Lesson 1
Introduction to Windows PowerShell

Windows PowerShell is the must-have environment for Windows administration


and automation, not just for Windows Server 2008, but also for Windows
Server 2003, Windows XP, and Windows Vista®.
In this lesson, you will be introduced to the role of Windows PowerShell in
Windows administration and automation. A demonstration of cmdlets and
pipelines provides a foundation for discussing the Windows PowerShell
architecture.
1-4 Introduction to Windows PowerShell™

What Is Windows PowerShell?

Key Points
In addition to being a scripting language and an interactive command shell,
Windows PowerShell is:
• An extensive environment
• An interpretive programming language platform

Windows PowerShell is focused on the administrator.

Question: How is Windows PowerShell different from other scripting languages,


such as VBScript and Perl?
Introduction to Windows PowerShell™ 1-5

Demonstration: Pipeline Processing in Windows PowerShell

Question: What is one way that you can combine commands or cmdlets in
Windows PowerShell?

Question: How can you use the modularity of cmdlets to perform a specific task?
1-6 Introduction to Windows PowerShell™

Windows PowerShell Architecture

Key Points
Windows PowerShell uses Microsoft .NET Framework version 2.0 as a foundation.
.NET Framework 2.0 and Windows PowerShell run on:
• Windows Server 2008
• Windows Vista
• Windows Server 2003
• Windows XP
• x86, x64, and Itanium-based architectures

Question: What are the benefits of having Windows PowerShell run on the
.NET Framework?

Additional Reading:
For more information on downloading Windows PowerShell, see Download
Windows PowerShell 2.0 CTP
Introduction to Windows PowerShell™ 1-7

The .NET Framework and Its Relationship to


Windows PowerShell

Key Points
The .NET Framework is the native foundation of Windows PowerShell.
Windows PowerShell is a scripting language for .NET objects in the same way that
VBScript is a scripting language for the COM.
Windows PowerShell is object-oriented, not merely text-oriented.

Question: How can you take advantage of the object-oriented nature of


Windows PowerShell?
1-8 Introduction to Windows PowerShell™

Use of WMI and COM in Windows PowerShell

Key Points
The Windows operating system supports object-oriented frameworks other
than .NET; for example, COM and WMI.
You can use combinations of objects from .NET, COM, and WMI frameworks
interactively, and in scripts, within the Windows PowerShell environment.

Question: How can you combine .NET, COM, and WMI objects to facilitate
your tasks?
Introduction to Windows PowerShell™ 1-9

Examples of Extensions to Windows PowerShell

Key Points
Windows PowerShell can be extended with:
• Providers
• Cmdlets
• Scripts, functions, aliases

Note: A commandlet (cmdlet) is a lightweight command used in the Windows


PowerShell environment.

Question: How does Exchange Management Shell (EMS) improve Windows


PowerShell capabilities?
1-10 Introduction to Windows PowerShell™

Lesson 2
Installing Windows PowerShell in
Windows Server 2008

In this lesson, you will see how to install Windows PowerShell using
Windows Server 2008 Server Manager. You will also see where
Windows PowerShell is installed and how to set the execution policy level to
RemoteSigned. In addition, you will see how to create a shortcut to the
Windows PowerShell executable.
Introduction to Windows PowerShell™ 1-11

Installing Windows PowerShell Using Server Manager

Key Points
You can use Server Manager in Windows Server 2008 to install
Windows PowerShell. Server Manager is available via Start, Administrative Tools.
Windows PowerShell requires .NET Framework (version 2.0 or version 3.0).
Windows Server 2008 comes with .NET Framework version 3.0 available as a
feature.
Windows Server 2008 includes Windows PowerShell version 1.0. Because the
.NET Framework does not yet run on Server Core, Windows PowerShell is limited
to full installations.

Question: Is your system a Full or a Server Core installation?


1-12 Introduction to Windows PowerShell™

Location of Windows PowerShell Executable and


Configuration Files

Key Points
Windows PowerShell is installed in the following path by default:
C:\Windows\System32\WindowsPowerShell\v1.0
Other files at this location include:
• The executable file Powershell.exe
• Support files, including these libraries:
• Pwrshmsg.dll
• Pwrshsip.dll
• Several configuration files

Subfolders contain documentation, localization files, and examples.

Question: Is there a benefit to viewing the installation folder in


Windows PowerShell?
Introduction to Windows PowerShell™ 1-13

Windows PowerShell Default Security Settings

Key Points
Windows PowerShell itself has many security features.
In addition, the way in which Windows handles Windows PowerShell by default
provides some security.

Question: What is the advantage of associating the .ps1 file extension with
Notepad rather than Windows PowerShell?
1-14 Introduction to Windows PowerShell™

Demonstration: Setting the Execution Policy


to RemoteSigned

Question: Prior to changing the execution policy, could you have run scripts?

Question: After changing the execution policy, can you run some scripts?
Introduction to Windows PowerShell™ 1-15

Demonstration: Creating a Shortcut to Windows PowerShell

Question: What is the advantage of adding a shortcut to Windows PowerShell?

Question: How would you run Windows PowerShell from a logon script?
1-16 Introduction to Windows PowerShell™

Lab: Implementing Windows PowerShell

Exercise 1: Installing Windows PowerShell


Scenario
You are a Windows Server 2008 administrator for Woodgrove Bank. You plan to
automate several Windows Server administration tasks by using Windows
PowerShell, in addition to using the shell for interactive systems management.
Therefore, you need to install Windows PowerShell on Windows Server 2008.
Knowing that Windows PowerShell depends on the .NET Framework, you will
first ensure that this framework is installed prior to installing Windows
PowerShell.

Exercise Overview
In this exercise you will select and install the correct build of
Windows PowerShell v1.0.
The main tasks for this exercise are as follows:
1. Start the 6434A-NYC-DC1 virtual machine and log on as Administrator.
2. Verify that the Windows PowerShell system requirements are met.
3. Install Windows PowerShell.
Introduction to Windows PowerShell™ 1-17

f Task 1: Start the 6434A-NYC-DC1 virtual machine and log on as


Administrator
• Start 6434A-NYC-DC1 and log on as Administrator using the password
Pa$$w0rd.

f Task 2: Verify that the Windows PowerShell system requirements are


met
• Ensure that .NET Framework v2.0 or later is installed.
• Ensure that the server operating system is compatible with
Windows PowerShell.
• Make a note of the server operating system and architecture (x64 or x86).

f Task 3: Install Windows PowerShell


• From the Administrative Tools menu, open Server Manager.
• Add the Windows PowerShell feature.

Results: After this exercise, you should have installed Windows PowerShell on
6434A-NYC-DC1.

Exercise 2: Customizing Windows PowerShell


Scenario
An administrator in your company, Woodgrove Bank, has a visual impairment and
cannot easily read the Windows PowerShell console when it is set to use the
default colors. You need to customize the console window to use different colors
that provide greater contrast. You also need to ensure that the shell can run scripts
that you and the other administrators at the bank have written, as well as
downloaded scripts that have been digitally signed.

Exercise Overview
In this exercise you will set the script execution policy in Windows PowerShell and
customize the appearance of the Windows PowerShell console window.
The main tasks for this exercise are as follows:
1. Set the script execution policy.
1-18 Introduction to Windows PowerShell™

2. Customize the appearance of the Windows PowerShell console window.

f Task 1: Set the script execution policy


• Set the script execution policy to RemoteSigned.

f Task 2: Customize the appearance of the Windows PowerShell console


window
• Configure the console window to have a buffer width of 100 characters and a
physical width of 80 characters.
• Configure the console window to have white text on a dark green background.
Feel free to change the colors to meet your personal preferences.
• Ensure that QuickEdit Mode is selected.

Results: After this exercise, you should have set the script execution policy to allow for
script execution, and customized the Windows PowerShell console window.
Introduction to Windows PowerShell™ 1-19

Lab Review
1-20 Introduction to Windows PowerShell™

Module Review and Takeaways

Review Questions
1. On which framework and runtime environment is Windows PowerShell
based?
2. What is the default installation path of Windows PowerShell?
3. What is the default execution policy security level in Windows PowerShell
version 1.0?
4. What are three kinds of objects that Windows PowerShell can work with?

Common Issues Related to Installation of Windows PowerShell


Identify the causes for the following common issues related to the installation of
Windows PowerShell and fill in the troubleshooting tips. For answers, refer to
relevant lessons in the module.

Issue Troubleshooting tip

Windows PowerShell will not install.

Scripts cannot be run in Windows


PowerShell.
Introduction to Windows PowerShell™ 1-21

Real-world Issues and Scenarios


1. You need to manage Active Directory® resources in a Windows Server 2008
domain controller, which has been installed using the Server Core installation
option. Windows PowerShell depends on the .NET Framework but the .NET
Framework is not supported on Server Core installations. Therefore, Windows
PowerShell cannot be installed directly on this domain controller. How can the
objects in Active Directory be managed in this domain controller using
Windows PowerShell?
2. You are using a Windows PowerShell script to manage Windows Server 2008.
Your manager asks if your scripts can be used to manage Windows 2000
Server or Windows 2000 Professional.

Best Practices Related to Installation of Windows PowerShell


Supplement or modify the following best practices for your own work situations:
• Install Windows PowerShell on Windows Server 2008 using the Full
installation option (not Server Core installation option) for local
administration and automation.
• Install Windows PowerShell on Windows Server 2003, Windows XP, or
Windows Vista for administration of those systems, or certain kinds of remote
administration of Windows Server 2008.
• Set the execution policy security level to RemoteSigned. This allows scripts
that are on the local computer to be run in Windows PowerShell, but requires
scripts that have been downloaded from remote locations to be signed with a
digital signature.

Tools

Tool Use for Where to find it


Get-ExecutionPolicy Showing the current Windows Windows PowerShell
PowerShell execution policy
security level

Set-ExecutionPolicy Changing the Windows Windows PowerShell


PowerShell execution policy
security level to a specific level
Overview of Windows PowerShell™ 2-1

Module 2
Overview of Windows PowerShell™
Contents:
Lesson 1: Overview of Objects 2-3
Lesson 2: Working with Cmdlets 2-9
Lesson 3: Tab Expansion, Aliases, and History 2-16
Lesson 4: Using Variables and Types 2-22
Lab: Working with Windows PowerShell Cmdlets, Aliases, Objects,
and Variables 2-28
2-2 Overview of Windows PowerShell™

Module Overview

You need a basic understanding of some of the mechanisms in Windows


PowerShell that focus on both interactive administration and scripting for
automation. This information serves as a foundation for many of the examples later
in this course.
This module explains basic concepts in Windows PowerShell, including objects,
variables, cmdlets, and pipelines. It describes how to invoke available cmdlets and
aliases and assign aliases. The module also includes demonstrations of tab
expansion and basic operators.
Overview of Windows PowerShell™ 2-3

Lesson 1
Overview of Objects

You need a basic understanding of the nature of objects and classes in an object-
based or object-oriented environment to understand the possibilities with
Windows PowerShell.
2-4 Overview of Windows PowerShell™

What Is an Object?

Key Points
An object can be more than just a set of data. An object can have properties that
describe the object instance in addition to methods that can act on the object
instance. Properties can be retrieved or updated.
Following is an example of changing a user interface with a property assignment:

$Host.UI.RawUI.ForegroundColor = “Blue”

Question: Are the consequences of changes to the representation changing the


real-world object always desirable?

Question: Can you control this feature?


Overview of Windows PowerShell™ 2-5

What Is an Object Class?

Key Points
An object class is the definition of the rules for an object: which properties are
allowed. An object class is used as a template. All object instances reflect the class
definition. All objects of the same class share similar traits, behaviors, and even
perhaps some attribute values.
An object is specifically referred to as an object instance to further reinforce that
there might be many objects of a given class.
The object class can also have static methods, which provide additional features for
all instances of that class.

Question: Can you think of examples of computer-based object-oriented class


systems?

Question: Can you think of examples of classes or instances?


2-6 Overview of Windows PowerShell™

Demonstration: Properties and Methods

Question: What information does Get-Member show for the processes in this
demonstration?

Question: How can this information be useful?


Overview of Windows PowerShell™ 2-7

Demonstration: Dot Notation for Member Access

Question: How would you use information that is revealed by Get-Member when
you use the dot operator with an object?

Question: Does the dot operator allow access to properties? Does the dot operator
allow access to methods?

Question: What do these capabilities allow you to do with processes (or other
objects)?
2-8 Overview of Windows PowerShell™

.NET, COM, and WMI Objects

Key Points
Windows PowerShell is based on the Microsoft .NET Framework and works with
.NET objects without any adaptation.
Windows PowerShell can automatically work with objects from many other
frameworks and subsystems, such as COM and WMI objects. Windows
PowerShell wraps these types of objects so that their interfaces are accessed in the
same way as .NET objects by interactive operations, scripts, and functions.
Most cmdlets can be used with any objects in Windows PowerShell, whether those
objects are based on the .NET Framework, COM, WMI, or other foundations.

Question: What is the advantage of being able to use many of the same cmdlets
with different kinds of objects?
Overview of Windows PowerShell™ 2-9

Lesson 2
Working with Cmdlets

Microsoft provides about 130 building blocks that perform many basic
administrative functions; these fundamental tools are called cmdlets.
This lesson focuses on the nature of cmdlets and some of the basic cmdlets
included in Windows PowerShell version 1.0. It is not meant to provide exhaustive
coverage of all of these cmdlets.
2-10 Overview of Windows PowerShell™

What Is a Cmdlet?

Key Points
Commandlets (cmdlets) are native Windows PowerShell commands. Each cmdlet
has a specific, typically small, task that it performs. Cmdlets are located in dynamic
link libraries (DLLs) known as snap-ins.
Windows PowerShell version 1.0 has over 130 built-in cmdlets. Extensions to
Windows PowerShell may include additional cmdlets.

Question: Which tasks would you like to perform with a cmdlet?


Overview of Windows PowerShell™ 2-11

Cmdlets and Their Parameters

Key Points
Cmdlets are named using a Verb-Noun naming convention, where the noun is
always singular. Cmdlets also take parameters that affect the operation of cmdlets.
Parameter names always begin with a "-". They can be abbreviated and, in some
cases, not specified.

Question: Why do you think consistent conventions are necessary for naming
cmdlets?
2-12 Overview of Windows PowerShell™

Demonstration: Listing Available Cmdlets (Get-Command)

Question: Which cmdlet can you use to obtain basic information about other
cmdlets, perhaps focusing on a particular noun or verb?
Overview of Windows PowerShell™ 2-13

Demonstration: Invoking Cmdlets from the Windows


PowerShell Prompt (Get-Help)

Question: Which cmdlet can you use to obtain detailed information about other
cmdlets and their parameters?
2-14 Overview of Windows PowerShell™

Parameters

Key Points
Cmdlet names are in the form Verb-Noun. Cmdlets accept parameters. The output
of cmdlets is objects.
Many cmdlets have a default behavior when they are used without parameters.
This is especially true of the Get-* cmdlets.
• Get-Date returns date and time information in many formats.
• Get-Process lists all processes by default, but when you give it a Name or Id
parameter, you can specify one or more names or process identifiers (comma
separated).
• Get-Help provides information about cmdlets and other topics. Cmdlet names
can be used as parameters to Get-Help.

Question: What are some abbreviated cmdlets that you would use frequently?

Question: What is the shortest unique form of these abbreviated cmdlets?


Overview of Windows PowerShell™ 2-15

Cmdlet Output

Key Points
Cmdlets can emit zero, one, or more objects.
If the output of a cmdlet is assigned to a variable, the objects are held in the
variable. Therefore, output is suppressed. Similarly, if an object emitted from one
cmdlet is sent down a pipeline, this output stays in object form.
To simplify the task of the administrator, the shell uses the default formatter to
convert the output objects to useful text.

Question: Can you come up with an analogy for this concept in other languages?
2-16 Overview of Windows PowerShell™

Lesson 3
Tab Expansion, Aliases, and History

A number of features of Windows PowerShell are designed to help administrators


type less and get their work done more quickly from the command line.
In this lesson you will see how to use tab expansion to help choose cmdlet names
and parameter names. Also, demonstrations of aliases that can be used
interactively or in scripts will illustrate how you can use easy-to-remember
mnemonics or abbreviations as shorthand for command or cmdlet names. You
also see how to use the history of recent commands to repeat operations that you
have performed previously.
Overview of Windows PowerShell™ 2-17

Features of Windows PowerShell

Key Points:
Several features of Windows PowerShell help to make interactive administration
and script writing easier. These include:
• Tab expansion: Expands cmdlet and parameter names
• History (F7): Helps to reduce retyping
• Aliases: Provides shortcut naming of cmdlets
• Profile: Enables you to define aliases in advance

Question: Which other features would you like to see in Windows PowerShell?
2-18 Overview of Windows PowerShell™

Demonstration: Using Tab Expansion

Question: Do you foresee any problems with using the tab expansion feature of
Windows PowerShell?
Overview of Windows PowerShell™ 2-19

Demonstration: F7 and History

Question: Which feature is more useful: command history or transcription? Why?


2-20 Overview of Windows PowerShell™

What Are Aliases?

Key Points
An alias refers to a cmdlet or a command element, such as a function, script, file, or
executable command. Aliases are useful substitutes for commonly used cmdlets
and also for infrequently used cmdlets.
There are about 100 predefined aliases, which fall into three categories:
• Brief abbreviations or acronyms (often two or three letters) for the natural
Windows PowerShell cmdlets (for example, gci for Get-ChildItem)
• Names similar to DOS or Windows command-prompt commands or built-ins
(for example, dir for Get-Childitem)
• Names similar to UNIX or Linux commands (for example, ls for Get-
Childitem)

Users can define their own names.

Question: Which aliases can you use to facilitate tasks on your job?
Overview of Windows PowerShell™ 2-21

Demonstration: Using the Set-Alias Cmdlet

Question: Which parameter must be used on the Set-Alias cmdlet so that aliases
defined in a script will be available in the shell console?
2-22 Overview of Windows PowerShell™

Lesson 4
Using Variables and Types

Pipelines and complex expressions largely mitigate the use of variables. However,
you still need a basic understanding of how variables can be used to understand
existing scripts and to write your own.
This lesson provides a foundation in the use of literal values (such as numbers and
strings), expressions (for example, arithmetic), and variables and types.
Overview of Windows PowerShell™ 2-23

What Is a Variable?

Question: Can you think of a scenario when you would put the output of a cmdlet
into a variable instead of letting the shell use the default formatter and output
cmdlets to display the objects.
2-24 Overview of Windows PowerShell™

What Is a Variable Type?

Key Points
Windows PowerShell uses the .NET Framework as its foundation. Therefore, it has
access to all .NET data types, COM objects, and WMI classes. If you assign the
output of the Get-Date cmdlet to the $now variable, the $now variable is of type
Date-Time. The output object takes on the type defined in the relevant class.
The example shown here is of one simple data type. Please refer to MSDN or
TechNet documentation for further details of this and other classes.
Question: Can you think of some data types that are used in other environments,
such as Microsoft Visual Basic® Scripting Edition (VBScript)?

Additional Reading:
For more information on variable types, see .NET Framework Class Library:
System Namespace
Overview of Windows PowerShell™ 2-25

Demonstration: Specifying a Variable Type

Question: Which notation is used to specify the type of a variable or value?


2-26 Overview of Windows PowerShell™

Basic Arithmetic Operators

Key Points
Windows PowerShell supports many operators.

Question: What is the difference between the / and % operators, and what is their
relationship?
Overview of Windows PowerShell™ 2-27

Assignment Operators

Key Points
Windows PowerShell supports several assignment operators.
The basic assignment operator is the equal sign (=), which simply takes the value
of the expression on the right of the equal sign and places the result in the variable
on the left of the equal sign.
Arithmetic assignment operators perform a binary operation on the initial value of
the variable on the left with the expression on the right, and then assign the result
to the variable on the left.
In Windows PowerShell, you can also specify the "++" or "--" at the beginning of the
variable name (for example, ++$count or --$airquality).

Question: What are some examples of practical uses of assignment operators in


Windows PowerShell?
2-28 Overview of Windows PowerShell™

Lab: Working with Windows PowerShell


Cmdlets, Aliases, Objects, and Variables

Exercise 1: Learning Cmdlets and Defining Aliases


Scenario
You are an administrator for Woodgrove Bank. You plan to automate several
Windows Server administrative tasks by using Windows PowerShell. To maximize
your efficiency with Windows PowerShell, you decide to create custom
abbreviations for the cmdlets that you will use most frequently. Therefore, you
need to learn the necessary cmdlets and define aliases for them. Many tasks that
you need to automate involve accessing the event logs; therefore, you decide to
start by finding cmdlets that work with the event logs. You also need a quick way
to save the output of Windows PowerShell operations in a file; consequently, you
also intend to find cmdlets that work with output and files.

Exercise Overview
In this exercise, you will identify the cmdlets necessary to perform specific tasks,
and you will create a new alias to one of those cmdlets.
The main tasks for this exercise are as follows:
Overview of Windows PowerShell™ 2-29

1. Start the 6434A-NYC-DC1 virtual machine, log on as Administrator, and start


Windows PowerShell.
2. Identify the cmdlets that perform a specific task.
3. Create an alias.

f Task 1: Start the 6434A-NYC-DC1 virtual machine, log on as


Administrator, and start Windows PowerShell
• Start 6434A-NYC-DC1 and log on as Administrator using the password
Pa$$w0rd.
• Open Windows PowerShell.

f Task 2: Identify the cmdlets that perform a specific task


• Identify the cmdlet that displays a list of Windows event log entries.
• Identify the cmdlet that pipes output to a specified text file.

f Task 3: Create an alias


• Create an alias named OF that references the cmdlet used to pipe output to a
specified text file.

Results: After this exercise, you should have identified two cmdlets and created an
alias for one of those cmdlets.

Exercise 2: Holding the Output of a Cmdlet


Scenario
You need to capture the output of a cmdlet so that the output can be used to
perform other tasks. You also want to be able to review the output at a later time.
At Woodgrove Bank, one of your administrative duties involves keeping track of
the processes that are running on your servers. You periodically need to make
snapshots of the list of processes running on each server; but occasionally, you
need to work with these lists right away. Therefore, you decide to keep the list of
processes in Windows PowerShell variable and then save the list of processes in
that variable to a text file.
2-30 Overview of Windows PowerShell™

Exercise Overview
In this exercise you will run a cmdlet and retain its output in a variable.
The main tasks for this exercise are as follows:
1. Obtain the currently running processes and store them in a variable.
2. Display the processes stored in a variable.

f Task 1: Obtain the currently running processes and store them in a


variable
• Use the Get-Process cmdlet to retrieve the currently running processes. Store
the results of the cmdlet in a variable named $processes.

f Task 2: Display the processes stored in a variable


• Display the processes stored in the $processes variable.
• Write the contents of $processes to a text file.

Results: After this exercise, you should have run a cmdlet and retained its output in a
variable. You should also have displayed the contents of that variable.
Overview of Windows PowerShell™ 2-31

Lab Review
2-32 Overview of Windows PowerShell™

Module Review and Takeaways

Review Questions
1. What are the basic arithmetic operators in Windows PowerShell?
2. Name three data types that are supported by Windows PowerShell.
3. Which characters can be used to delimit a string value?
4. What are four features of Windows PowerShell that can help make interactive
administration and script writing easier?

Common Issues Related to Cmdlets and Aliases


Identify the causes for the following common issues related to cmdlets and aliases
and fill in the troubleshooting tips. For answers, refer to relevant lessons in the
module.

Issue Troubleshooting tip

The values, variables, and special Be sure to use quotation marks (") rather than
characters within a string literal are apostrophes (') when specifying string literals
not substituted. in which you need to have variable and special
character value substitution occur.
Overview of Windows PowerShell™ 2-33

Issue Troubleshooting tip

An alias defined in a script is not Use the -Scope Global parameter on the
available outside the script. Set-Alias cmdlet to ensure that the alias is
defined outside the script.

While attempting to refer to a Enclose the cmdlet or pipeline in parentheses;


property of an object returned by a then follow this with the dot operator and
cmdlet, you get an error indicating then the property of the resultant object. For
that this is not recognized as a example, use (Get-Date).Month rather than
cmdlet, function, operable program, Get-Date.Month.
or script file.

Real-world Issues and Scenarios


1. You need to learn more about the cmdlets in Windows PowerShell.
2. You need to understand more about the operators and language syntax in
Windows PowerShell.

Best Practices Related to Using Cmdlets and Variables


Supplement or modify the following best practices for your own work situations:
• Simply use a cmdlet or pipeline of cmdlets when the resultant objects are
intended to be displayed on the console.
• Put the cmdlet (or pipeline) in parentheses when you need to refer to it as an
object. This is useful not only with the dot operator for member access, but
also when you are using the output of cmdlets in other expressions or as
parameters to other cmdlets.
• Assign the output of a cmdlet to a variable when you need to do several
operations with the resultant objects, or when other cmdlets or code might be
used between getting the output of the cmdlet and using it.

Tools

Tool Use for Where to find it


Get-Command Discovering cmdlets and their Windows PowerShell
basic syntax

Get-Help Discovering details of cmdlets Windows PowerShell

Set-Variable Assigning a value to a variable Windows PowerShell


2-34 Overview of Windows PowerShell™

Tool Use for Where to find it


Set-Alias Assigning a value to an alias Windows PowerShell
Building Pipelines for Assembly-Line Style Processing 3-1

Module 3
Building Pipelines for Assembly-Line Style
Processing
Contents:
Lesson 1: Using Pipelines 3-3
Lesson 2: Using Arrays 3-9
Lesson 3: Filtering and Iterating Through the Pipeline 3-15
Lesson 4: Reordering Objects in a Pipeline 3-21
Lab: Implementing Pipelines in Windows PowerShell 3-25
3-2 Building Pipelines for Assembly-Line Style Processing

Module Overview

Arrays and pipes are fundamental building blocks for interactive scripting in
Windows PowerShell.
This module explains how to use a pipeline to connect the output of one cmdlet to
the input of another, reorder objects, and filter objects based on specific properties.
Arrays and their uses are also discussed.
Building Pipelines for Assembly-Line Style Processing 3-3

Lesson 1
Using Pipelines

Pipelines are a principal language element in Windows PowerShell, as evidenced


by the pipeline processor. Any automation endeavors based on Windows
PowerShell should consider full use of pipelines.
3-4 Building Pipelines for Assembly-Line Style Processing

What Is a Pipeline?

Key Points
You can use a pipeline to directly connect the output of the first cmdlet to the
input of the second cmdlet.
You do not need to create a temporary file. The flow of data through the pipeline
from one cmdlet to another is managed by the shell.
The information (data) flowing from one cmdlet to another via the pipeline is in
the form of objects.

Question: What is the advantage of using a pipeline?


Building Pipelines for Assembly-Line Style Processing 3-5

Multistage Pipelines

Key Points
For more complex processing, you can chain together a series of cmdlets using a
sequence of pipes. For each stage of the pipeline, the output of one cmdlet is piped
into the input of the next cmdlet.

Question: Why would you use a multistage pipeline?


3-6 Building Pipelines for Assembly-Line Style Processing

Pipeline Processing Architecture

Key Points
The Windows PowerShell pipeline processor is a software module that governs the
flow of objects through a pipeline.
The input and output streams of each cmdlet are handled by the pipeline
processor.

Question: How does the Windows PowerShell pipeline processor manage the
input and output of the cmdlets in a pipeline?
Building Pipelines for Assembly-Line Style Processing 3-7

Using the InputObject Parameter Instead of a Pipeline

Key Points
The InputObject parameter is accepted by many cmdlets (37 out of 129). With this
parameter, you can specify a variable to use as input rather than using a pipeline.

Question: Can you think of an example when it would be better to use the
InputObject parameter instead of a pipeline?
3-8 Building Pipelines for Assembly-Line Style Processing

Using Pipelines for Calculations

Key Points
Measure-Object has several parameters that govern which calculations to perform
on its input objects.

Question: Which calculations can the Measure-Object cmdlet perform?


Building Pipelines for Assembly-Line Style Processing 3-9

Lesson 2
Using Arrays

Arrays can be used in many ways in their own right, but they can also be used with
pipeline processing.
3-10 Building Pipelines for Assembly-Line Style Processing

Scalar vs. Array Variables

Key Points
Scalars represent one value. Literals, expressions, and variables can all be scalars,
and are scalar in cases when they represent, evaluate to, or hold one value.
Arrays can hold lists of basic values or lists of complex objects. Arrays can be used
to represent a collection of objects that is a result of one cmdlet or function.

Question: Can you think of some uses for arrays? What could they hold?

Question: How would values be put into an array?

Question: How would these values be referred to later?

Additional Reading:
• For more information about the @() notation, see Windows PowerShell: Array
Literals in PowerShell
• For more information about the capabilities of arrays in Windows PowerShell,
see VBScript to Windows PowerShell: Converting VBScript's LBound Function
Building Pipelines for Assembly-Line Style Processing 3-11

Associative Arrays

Key Points
Whereas basic arrays, are integer-indexed, associative arrays are indexed by name,
Each name is associated with a value. An empty associative array is specified as @{}.
Associative array indexes are keys that must be unique. Instead of using unique
integers, unique names are used.
Each value of an associative array consists of a key and a value separated by an
equal sign. If the name of the key includes spaces, the name must be quoted. If the
value is not numeric, but is a string value, it also should be quoted. Specify
multiple key/value pairs in the @{} set, with the semicolon separating each pair.

Question: What is the difference between an integer-indexed array and an


associative array?

Additional Reading:
For more information about collections and hash tables, see:
• Commonly Used Collection Types
• Hashtable and Dictionary Collection Types
3-12 Building Pipelines for Assembly-Line Style Processing

Associative Array Assignment

Key Points
You can add new values to existing arrays by using the assignment operator (equal
sign) to assign one value within the array. The assignment operator replaces a
whole array when the whole array is on the left side of the equal sign.
The list operator (comma) is used to separate values in a list. The range operator
(dot dot) is used to specify a range of values in a list.
Associative arrays are assigned by specifying their values using @{} notation.

Question: How would you assign the numbers 1 through 100 to an array?
Building Pipelines for Assembly-Line Style Processing 3-13

Array Operators

Key Points
Arrays can be added using the addition (plus sign) + operator. The plus equal (+=)
operator can also be used to add to an array.
Individual values of arrays are referred to by index. Subsets of arrays can be
extracted by referring to a range or list of values.

Question: How would you add two arrays together?


3-14 Building Pipelines for Assembly-Line Style Processing

Associative Array Dot Operator

Key Points
The dot operator can be used to refer to a member of an associative array. This
operator is similar to the property operator for objects.

Question: How is using the dot operator to access a member of an associative


array similar to using the dot operator to access a property of an object?
Building Pipelines for Assembly-Line Style Processing 3-15

Lesson 3
Filtering and Iterating Through the Pipeline

A number of built-in cmdlets provide the ability to work with objects in a pipeline,
including filtering some objects and iterating through a list of objects.
This lesson provides an introduction to using these cmdlets and techniques to
iterate through a collection of objects.
3-16 Building Pipelines for Assembly-Line Style Processing

Filtering Objects Using the Where-Object Cmdlet

Key Points
You can filter objects using the Where-Object cmdlet. A collection of objects comes
in as a stream to the filtering mechanism of the Where-Object. This approach is
also known as late filtering.
The code block for Where-Object is evaluated as a condition and is filtered as
follows:
• When true, Where-Object emits the current object.
• When false, Where-Object abandons further processing of the current object.

In this approach, the previous cmdlet in the pipeline generates a collection of


objects, which Where-Object filters. If there is no previous cmdlet in the pipeline,
the objects are passed to Where-Object via the InputObject parameter.
Only certain objects (between zero and the whole collection from the previous
cmdlet) are chosen by the filter in the condition code block of Where-Object and
emitted or relayed further along the pipeline.

Question: In which instances would you need to filter objects?


Building Pipelines for Assembly-Line Style Processing 3-17

Filtering Within Cmdlets

Key Points
You can filter objects within some cmdlets by using the Filter, Include, and
Exclude parameters. This approach is also known as early filtering. In general, this
approach is more efficient than late filtering, but not all cmdlets support early
filtering.
The Filter parameter is processed within the cmdlet, which is often (but not
necessarily) a cmdlet that is being used early in a pipeline. This approach reduces
the dependence on the pipeline and other cmdlets such as Where-Object so that
the effective cmdlet sequence is potentially more efficient and performs faster.
The Include and Exclude parameter values can include wildcards.
The syntax and semantics for the Filter parameter value depend on the provider
that is being used.

Question: Which cmdlets can you use to list the cmdlets available with the Filter,
Include, and Exclude parameters?
3-18 Building Pipelines for Assembly-Line Style Processing

Demonstration: Using Where-Object for Files

Question: What must the value of the expression in the code block of
Where-Object evaluate to so that an object will be emitted by Where-Object?
Building Pipelines for Assembly-Line Style Processing 3-19

Two Variants of foreach: Construct and Cmdlet

Key Points
The foreach construct iterates through an associative or a basic array (collection),
usually a variable, element by element, assigning a specifically named variable to
the current element of the collection. It then runs the code block for that element.
The ForEach-Object cmdlet typically takes input from a pipeline, and assigns each
object to a special variable, $_. It then invokes the code block for that object.

Question: Can you think of scenarios when you would use the ForEach-Object
cmdlet rather than the foreach construct?
3-20 Building Pipelines for Assembly-Line Style Processing

Iterating Through Objects Using the ForEach-Object


Cmdlet

Key Points
ForEach-Object works with a pipeline much like Where-Object does. The
difference is that ForEach-Object iterates through each object by executing its code
block for the object, whereas Where-Object has only a condition in its code block
that governs which objects coming down the pipeline are emitted to the next stage.
The ForEach-Object cmdlet typically has two aliases:
• foreach, which is chosen instead of the construct by that name based on
syntax differences
• %, which is pronounced “each” rather than “percent”

Question: How does ForEach-Object differ from Where-Object?


Building Pipelines for Assembly-Line Style Processing 3-21

Lesson 4
Reordering Objects in a Pipeline

You can use the Sort-Object cmdlet to explicitly control the order of objects
according to specific criteria. In addition, the Select-Object cmdlet provides a
mechanism to control which objects are selected or which properties of the
resultant objects are selected. These cmdlets are often used at or toward the end of
a pipeline.
3-22 Building Pipelines for Assembly-Line Style Processing

Reordering Objects with the Sort-Object Cmdlet

Key Points
The Sort-Object cmdlet sorts a pipeline of objects by the values of any property in
either ascending or descending order.

Question: Can you think of some situations that would benefit from
reordering objects?
Building Pipelines for Assembly-Line Style Processing 3-23

Demonstration: Using the Sort-Object Cmdlet for Files

Question: How would you sort by modification time of a file?

Question: How would you sort by file size so that the biggest files appear first in
the list?
3-24 Building Pipelines for Assembly-Line Style Processing

Demonstration: Choosing Specific Properties of Objects


Using the Select-Object Cmdlet

Question: How would you obtain a list of the five most recent files in the current
folder?

Question: How would you obtain a list of the five biggest processes according to
virtual memory size?
Building Pipelines for Assembly-Line Style Processing 3-25

Lab: Implementing Pipelines in


Windows PowerShell

Exercise 1: Evaluating Process Properties Using the


Get-Member Cmdlet
Scenario
You need to use Windows PowerShell to perform several tasks related to running
processes. In order to do so, you need to identify the appropriate process object
properties. The servers that you manage at Woodgrove Bank must be monitored
with respect to virtual memory utilization and physical memory utilization,
including the amount of non-paged memory that is being used. These memory
utilizations must be tracked per process so that you can evaluate which processes
are the biggest consumers, and so that you can track growth in memory
utilizations over time due to increasing traffic through the services hosted by your
servers.

Exercise Overview
In this exercise you will use the Get-Member cmdlet to identify various properties
of a Process object.
The main tasks for this exercise are as follows:
3-26 Building Pipelines for Assembly-Line Style Processing

1. Start the 6434A-NYC-DC1 virtual machine, log on as Administrator, and start


Windows PowerShell.
2. Identify specific properties of a Process object.

f Task 1: Start the 6434A-NYC-DC1 virtual machine, log on as


Administrator, and start Windows PowerShell
• Start 6434A-NYC-DC1 and log on as Administrator using the password
Pa$$w0rd.
• Open Windows PowerShell.

f Task 2: Identify specific properties of a Process object


• Use Windows PowerShell to display all the properties for a Process object.
• Examine the list of Process object properties to determine the properties that
represent the following aspects of the process:
• Virtual memory utilization
• Paged memory utilization
• Non-paged memory utilization

Results: After this exercise, you should have discovered the Process object properties
that represent the virtual memory utilization, paged memory utilization, and non-
paged memory utilization of a process.

Exercise 2: Calculating Process Memory Usage


Scenario
Lately at Woodgrove Bank, concerns have been raised as to whether your servers
have adequate RAM to deal with the increased traffic load created by many new
users after a recent merger. You need to identify which services and applications
are consuming the most memory. In order to narrow down which processes are
responsible for high memory consumption, you need to calculate and display the
amount of memory used by the processes running on a server.
Building Pipelines for Assembly-Line Style Processing 3-27

Exercise Overview
In this exercise, you will use Windows PowerShell to calculate the memory usage
for the processes running on a computer.
The main tasks for this exercise are as follows:
1. Display memory utilization statistics for running processes.

f Task 1: Display memory utilization statistics for running processes


• Display the average paged memory used by all running processes.
• Display the total virtual memory used by all running processes.
• Display the average, total, minimum, and maximum values for virtual and
paged memory utilization by all running processes.

Results: After this exercise, you should have displayed various memory utilization
statistics for the processes running on a computer.

Exercise 3: Using Associative Array Variables


Scenario
You monitor many of the servers in the data centers of Woodgrove Bank remotely
from a central network operation center. You use powerful systems management
products to accomplish some of your goals, but some tasks are best handled with
custom Windows PowerShell scripts. One of the scripts that you are writing needs
to keep track of the computer name, primary management IP address, and the
operating system that the server is running. You need to create an associative array
to store multiple pieces of information in a single variable, and utilize the array to
access specified pieces of information.

Exercise Overview
In this exercise you will create and utilize an associative array.
The main tasks for this exercise are as follows:
1. Create an associative array and populate it with values.
2. Display specified members of an associative array.
3-28 Building Pipelines for Assembly-Line Style Processing

f Task 1: Create an associative array and populate it with values


• Create an associative array and store it in a variable named $arr. Populate the
array with the following key/value pairs:
• Name/Server2
• IP/192.168.10.10
• OS/Windows Server 2008

f Task 2: Display specified members of an associative array


• Using the variable $arr created in Task 1, display only the value for the IP key.

Results: After this exercise, you should have created an associative array and displayed
specific values from within the array.

Exercise 4: Sorting and Selecting Elements from a


Resultant Set of Data
Scenario
You have determined that the amount of physical memory in some of the servers
that you administer at Woodgrove Bank is inadequate. You need to create a report
that describes the processes that are running on a server. You need to sort this set
of objects so that they appear in the correct order, and ensure that only the
necessary object property values are displayed. You decide to sort by the physical
memory used by each process, with the largest consumer at the beginning of the
list and the process with the smallest memory footprint at the end of the list. In
order to focus on only the necessary information, you then decide to report only
the process names and physical memory utilization values, and also to limit the list
to the top ten processes that are using disproportionately large amounts of
memory.

Exercise Overview
In this exercise you will retrieve the currently running processes and display them
in a sorted table that includes a subset of the processes and their properties.
The main tasks for this exercise are as follows:
1. Sort processes into the desired order.
2. Select the desired properties of a process.
Building Pipelines for Assembly-Line Style Processing 3-29

3. Select a subset of the available processes.

f Task 1: Sort processes into the desired order


• Use the Get-Process cmdlet to retrieve all running processes. Sort them so that
the processes using the most paged memory are displayed first.

f Task 2: Select the desired properties of a process


• Use the Get-Process cmdlet to retrieve all running processes. Sort them so that
the processes using the most paged memory are displayed first. Format the
output so that it is displayed as a table that includes only the names of the
processes and paged memory utilization.

f Task 3: Select a subset of the available processes


• Use the Get-Process cmdlet to retrieve all running processes. Sort them so that
the processes using the most paged memory are displayed first. Format the
output so that it is displayed as a table that includes only the names of the
processes and paged memory utilization. Display only the first 10 processes.

Results: After this exercise, you should have created a table that displays a sorted
subset of running processes.
3-30 Building Pipelines for Assembly-Line Style Processing

Lab Review
Building Pipelines for Assembly-Line Style Processing 3-31

Module Review and Takeaways

Review Questions
1. How does a pipeline connect cmdlets?
2. What is the name of the Windows PowerShell software module that manages
the pipeline connections between cmdlets?
3. How are associative arrays initialized?
4. Which cmdlet selects a subset of its objects based on a condition in a code
block?
5. Which cmdlet runs a code block for each of its elements?
6. Which cmdlet enables sorting the objects that it receives?
3-32 Building Pipelines for Assembly-Line Style Processing

Common Issues Related to Sorting and Filtering


Identify the causes for the following common issues related to sorting and filtering
and fill in the troubleshooting tips. For answers, refer to relevant lessons in the
module.

Issue Troubleshooting tip


There is too much data in a data set.

You need to repeat a calculation of


a sequence of numbers or strings.

The data is in the wrong order.

Only the first or last of so many


elements are needed from a data
set.

Real-world Issues and Scenarios


1. You need a report of the top consumers of virtual memory and RAM on a
server.
2. You need a report of the largest files in a subtree.

Best Practices Related to Arrays and Operators


Supplement or modify the following best practices for your own work situations:
1. Use arrays and the range operator to simplify iteration through a number of
values.
2. Use the foreach construct for iterating through an array, but use the
ForEach-Object cmdlet for iterating through a pipeline.
3. Use the Measure-Object cmdlet for calculating sums and averages.
4. Use Get-Command | Where-Object { $_.Definition -match "pattern" } to find
cmdlets that support a particular parameter.
Building Pipelines for Assembly-Line Style Processing 3-33

Tools

Tool Use for Where to find it


Where-Object cmdlet Filtering some objects in a Windows PowerShell
pipeline

ForEach-Object cmdlet Iterating through a sequence of Windows PowerShell


objects in a pipeline

Foreach construct Iterating through an array of Windows PowerShell


objects

Sort-Object cmdlet Reordering the objects in a Windows PowerShell


pipeline

Select-Object cmdlet Choosing some objects or Windows PowerShell


properties in a pipeline

Measure-Object cmdlet Calculating average, sum, and Windows PowerShell


more for a property of all of the
objects in a pipeline

Get-Process cmdlet Listing the processes running on Windows PowerShell


the system

Get-ChildItem cmdlet Listing the files and folders in the Windows PowerShell
current location

Get-Member cmdlet Listing properties and methods of Windows PowerShell


objects

Get-Command cmdlet Listing cmdlets. Windows PowerShell


Managing Processes and Formatting Cmdlet Output 4-1

Module 4
Managing Processes and Formatting Cmdlet
Output
Contents:
Lesson 1: Managing Windows® Processes with Windows PowerShell 4-3
Lesson 2: Formatting Cmdlet Output 4-9
Lab: Output Formatting and Process Control with Windows PowerShell 4-16
4-2 Managing Processes and Formatting Cmdlet Output

Module Overview

Management of processes provides many opportunities for working with data


formatting. This module uses the get-process and get-service cmdlets to
demonstrate both key Windows PowerShell features and to show how to manage
processes and services.
This module also explains how Windows PowerShell™ formatting works.
Windows PowerShell enables you to choose a format in which to present data that
is appropriate to the data set, format specific process properties, such as memory
usage or CPU time, and use custom formatting.
Managing Processes and Formatting Cmdlet Output 4-3

Lesson 1
Managing Windows® Processes with
Windows PowerShell

Server administration often involves management of the processes and services


that are executing on the system. This lesson focuses on use of the
System.Diagnostics.Process object and the Get-Process cmdlet.
4-4 Managing Processes and Formatting Cmdlet Output

Viewing Process Details

Key Points
The Get-Process cmdlet returns a list of processes that are currently running on the
computer. The list is returned as a collection of objects that you can sort, select, or
format.

Question: Which properties are included by default in the list of processes that are
returned by Get-Process?
Managing Processes and Formatting Cmdlet Output 4-5

Filtering Processes by Property

Key Points

You can select one or more specific processes by using the Where-Object cmdlet
(aliased as “?”).
You can find the collection of properties and methods that are available on a
process by using the Get-Member cmdlet.

Question: Which other properties would you like to see for a process?
4-6 Managing Processes and Formatting Cmdlet Output

Stopping Processes

Key Points
You can keep references to one or more processes in variables. You can take
actions on these processes using the methods on the process variable.
Many Get-* cmdlets support some property selection criteria so that Where-Object
in a pipeline is not required in the most basic scenarios. This is true with
Get-Process.
A method is invoked by using parentheses after its name, and optionally supplying
parameters in the parentheses.
You can stop a process by using the Stop-Process cmdlet instead of the Kill
method.

Note: There is no "Are you sure" message when you kill a process.

Question: How could you close all copies of Microsoft Word on the computer
prior to updating the software?
Managing Processes and Formatting Cmdlet Output 4-7

Launching Processes

Key Points
Processes can be launched using any classic Windows approach. You can start a
process simply by typing its file name at a Windows PowerShell prompt.
You can use Invoke-Item to open a file using file extension activation.
The static method [System.Diagnostics.Process]::Start supports several
arguments for running processes.

Question: How would you launch a process using alternate credentials?


4-8 Managing Processes and Formatting Cmdlet Output

Viewing, Starting, and Stopping Services

Key Points
Windows PowerShell 1.0 comes with eight cmdlets for working with Windows
services.
You can also use the Get-WMIObject cmdlet specifying the Win32_Service class
name.
Get-Process provides details on running services.

Question: Which cmdlets would you use to start, stop, or restart services?
Managing Processes and Formatting Cmdlet Output 4-9

Lesson 2
Formatting Cmdlet Output

The sheer volume of information available to administrators via Windows


PowerShell can be overwhelming. This information must be properly filtered and
managed. Administrators have a substantial set of tools designed for formatting
information.
This lesson focuses on the most pertinent formatting cmdlets and operators for
controlling management information. Such formatting techniques can easily be
used in all scripts and interactive duties performed in Windows PowerShell.
4-10 Managing Processes and Formatting Cmdlet Output

Default Formatter and Output Cmdlets

Key Points
If objects are left in the pipeline, then Windows PowerShell uses the default
formatter to create output. Windows PowerShell pipes all remaining objects to the
Out-Default cmdlet by default
You can also specify a specific formatter and format by piping objects to the
format-* cmdlets (for example, Format-Table and Format-List).

Question: Which default formatter is used with information retrieved


by Get-Process?

Question: Where does the output go by default?


Managing Processes and Formatting Cmdlet Output 4-11

Alternatives to the Out-Default Cmdlet

Key Points
Usually, output is processed by the Out-Default cmdlet. Alternatively, output can
be piped to a specific output handler for sending to a printer, a file, the host
(console), or string. Output can be sent to graphical tools using third-party
cmdlets.

Question: What are the benefits of using alternative means of processing output?
4-12 Managing Processes and Formatting Cmdlet Output

Default Formatting in Windows PowerShell

Key Points
Windows PowerShell first uses a built-in XML display specification to format an
object. If a default view is not specified in the XML display, Windows PowerShell
looks at the number of properties to be displayed. It then chooses between the
Format-Table and Format-List cmdlets, depending on the number of properties to
format.
You can explicitly choose which output format Windows PowerShell should use,
including Format-Table, Format-List, Format-Wide, or Format-Custom. Simply add
the specific formatter explicitly at the end of the pipeline.

Question: Which type of output is most suited to Format-Table and Format-List?

Question: When would you use Format-Wide and Format-Custom?


Managing Processes and Formatting Cmdlet Output 4-13

Using the Format-Wide, Format-Table, Format-List, and


Format-Custom Cmdlets

Key Points
The formatting cmdlets perform the following functions:
• Format-Wide shows a limited set of properties in a small space.
• Format-Table shows data in tabular form.
• Format-List shows many details.
• Format-Custom uses views in .PS1XML files to show advanced formatting that
does not fit into the list or table model.

Question: How do you get a brief list of the files in a folder?


4-14 Managing Processes and Formatting Cmdlet Output

Selecting Properties Using Select-Object

Key Points
The Select-Object cmdlet has four functions.
• Selecting a partial attribute set: It selects a partial attribute set of each of the
input objects and emits these same objects without the excluded properties.
• Selecting unique objects: It selects the unique set of objects from the inbound
collection.
• Selecting the first n or last n objects: It emits the first several or last several
objects from the inbound collection and eliminates the rest.
• Selecting calculated properties: It adds new properties to each of the objects in
the inbound collection before emitting each into the output stream.

Question: Which of the four functions of the Select-Object cmdlet would be the
most useful on your job?
Managing Processes and Formatting Cmdlet Output 4-15

Formatting Strings with the -f Operator and .NET

Key Points
The Microsoft .NET Framework includes a string formatting method that is
available in Windows PowerShell with the -f operator.
You can use the -f (formatting) operator in expressions and variable assignments
as a parameter to functions or cmdlets.
Embedding literal strings and many variable values within one output string helps
to avoid a large number of string concatenation operators. This approach tends to
yield more readable scripts than the catenation approach. You are in control of
how your output looks.

Question: How would you format a number using the -f operator?

Additional Reading:
For more information about the .NET format operator notation, see .NET Format
String 101. The examples are specified using C#, but you can translate them to
Windows PowerShell for your own use.
4-16 Managing Processes and Formatting Cmdlet Output

Lab: Output Formatting and Process Control


with Windows PowerShell

Exercise 1: Implementing Basic Formatting Control


Scenario
You are an administrator for Woodgrove Bank. You need to format the output of
Windows PowerShell cmdlets so that administrative information is displayed in an
appropriate manner. Three of the common types of data that you work with are
services, event log entries, and processes. You choose an appropriate formatting
cmdlet to suit each type of data and the task at hand. In addition, you choose
specific properties of the different kinds of objects you work with so that both the
format and specific data that is presented in that format is easy to understand.

Exercise Overview
In this exercise you will use formatting cmdlets to create basic customized
formatting.
The main tasks for this exercise are as follows:
1. Start the 6434A-NYC-DC1 virtual machine, log on as Administrator, and start
Windows PowerShell.
2. Format services in a table.
Managing Processes and Formatting Cmdlet Output 4-17

3. Format event log entries in a list.


4. Format processes in a wide list.

f Task 1: Start the 6434A-NYC-DC1 virtual machine, log on as


Administrator, and start Windows PowerShell
1. Start 6434A-NYC-DC1 and log on as Administrator using the password
Pa$$w0rd.
2. Open Windows PowerShell.

f Task 2: Format services in a table


• Display a list of installed services in a table, so that the table includes columns
only for the name and current status (running or stopped) of the services. The
table should not span the width of the Windows PowerShell window.
• Display a list of installed services in a table, so that the table includes columns
only for the name, current status (running or stopped) services, and whether
or not the service can be paused.

f Task 3: Format event log entries in a list


• Display the 20 most recent System event log entries in a list. The list should
include all properties of the event log entry objects.

f Task 4: Format processes in a wide list


• Display a two-column list of currently running process names.
• Display a two-column list of currently running process descriptions.

Results: After this exercise, you should have five custom-formatted displays for various
operating system object types.
4-18 Managing Processes and Formatting Cmdlet Output

Exercise 2: Formatting with the -f Operator


Scenario
You are creating a script that will display messages regarding running processes.
Your manager at Woodgrove Bank expects clear and concise information that is
presented in an easy to understand format. You need to present her with
information about the memory utilization of specific processes at various points in
time. You need to insert formatted data into the messages so that the messages
have a clear meaning. You have chosen to use the–f formatting operator of
Windows PowerShell to help in this task.

Exercise Overview
In this exercise, you will use the -f operator to provide custom formatting for
various operating system objects and data.
The main tasks for this exercise are as follows:
1. Insert data into a string.
2. Insert numerically formatted data into a string.
3. Insert date-formatted data into a string.

f Task 1: Insert data into a string


• Retrieve all running processes and store them in a variable named $processes.
• Use the -f operator to display the string, "The second process is x," so that "x" is
the name of the second process in $processes.
• Use the -f operator to display the string, "The second process is x, and it is
using y bytes of virtual memory," so that "x" is the name of the second process
in $processes, and "y" is the amount of virtual memory being used by that
process.

f Task 2: Insert numerically formatted data into a string


• Retrieve all running processes and store them in a variable named $processes.
• Use the -f operator to display the string, "The second process is x, and it is
using yMB of virtual memory," so that "x" is the name of the second process in
$processes, and "y" is the amount of virtual memory being used by that
Managing Processes and Formatting Cmdlet Output 4-19

process. Display the virtual memory in megabytes, formatted as a number with


no digits after the decimal point.

f Task 3: Insert date-formatted data into a string


• Use the Get-Date cmdlet to retrieve the current date and store it in a variable
named $now.
• Display the string, "Today is x," where "x" is the current date formatted as a
short date (such as MM/DD/YYYY or DD/MM/YYYY, depending on the
regional settings of your computer).

Results: After this exercise, you should have produced various strings that include
formatted data.

Exercise 3: Implementing Advanced Formatting


Scenario
You are creating a formatted report for your supervisor and need to ensure that the
report contains the correct data. Your supervisor is the director of IT at Woodgrove
Bank, and she is very busy. You want to ensure that the units of information that
you are reporting are consistent with other reports that she uses. Some of the
necessary data needs to be calculated using a mathematical expression.
Specifically, the virtual memory utilization of processes should be reported in units
of megabytes rather than in units of bytes. However, the available data is provided
in units of bytes. You decide to test the expression and reporting format and then
generate the report by providing a calculated property to the Windows PowerShell
table formatter.

Exercise Overview
In this exercise you will use the Format-Table cmdlet to implement advanced
formatting, including calculated columns in a table.
The main tasks for this exercise are as follows:
1. Prototype a calculated column using the -f operator
2. Create a table that contains a calculated column
4-20 Managing Processes and Formatting Cmdlet Output

f Task 1: Prototype a calculated column using the -f operator


• Retrieve a list of processes into a variable named $processes.
• Use the -f operator to display the virtual memory utilization of the first process
in $processes. The virtual memory utilization should be displayed in
megabytes, using numeric formatting, with no digits after the decimal point.

f Task 2: Create a table that contains a calculated column


• Display a list of all running processes in a table that includes the names of the
processes and their virtual memory utilization. The virtual memory utilization
should be displayed in megabytes, using numeric formatting, with no digits
after the decimal point.

Results: After this exercise, you should have created a table that uses a calculated
column.
Managing Processes and Formatting Cmdlet Output 4-21

Lab Review
4-22 Managing Processes and Formatting Cmdlet Output

Module Review and Takeaways

Review Questions
1. How would you find the complete list of properties that could be present on a
process?
2. How would you find the complete list of properties that could be present on a
process?
3. Which formatting cmdlet presents one property of a number of objects with
different objects shown in different columns?
4. Which formatting cmdlet presents many properties of a number of objects
with one property per column?
5. Which cmdlet can be used to include calculated properties?
Managing Processes and Formatting Cmdlet Output 4-23

Common Issues related to Selecting and Formatting Output


Identify the causes for the following common issues related to selecting and
formatting output and fill in the troubleshooting tips. For answers, refer to relevant
lessons in the module.

Issue Troubleshooting tip


When using Select-Object with the
Unique parameter, you receive only
one object as output.

Using the -f operator results in an


error formatting a string "Index
(zero based) must be greater than or
equal to zero and less than the size
of the argument list."

Real-world Issues and Scenarios


1. One of your servers is having performance issues that seem to be related to
limited RAM. In order to research which software is consuming the most
memory, you need to determine the top 10 processes according to memory
usage. How would you do this in Windows PowerShell?
2. You need to apply an update, hot fix, or service pack to some of your servers.
One of the changes identified by a particular hot fix is that some DLL files are
updated. In order to determine which software and services on your servers
will potentially be impacted by this change, you need to list the services that
are using a particular DLL. How would you find the services using a given DLL
using Windows PowerShell?
3. In monitoring your servers, you find that a particular user is consistently over
quota every week. In the past you have noted that this user often downloads
large files to his Documents folder subtree and then forgets to delete them.
You need to find the 15 biggest files in a folder as an automated task. How
would you implement the part of this task which finds the 15 biggest files in a
folder or folder subtree?
4-24 Managing Processes and Formatting Cmdlet Output

Best Practices related to Selecting and Formatting Output


Supplement or modify the following best practices for your own work situations:
• Use .NET format strings with the -f operator to simplify complex processing of
output formats.
• Use the Select-Object cmdlet in conjunction with the Sort-Object and/or
Group-Object cmdlets to control which properties are included in a specific
order.
• Use the Format-Wide, Format-List, Format-Table, or Format-Custom cmdlets
to control the presentation of objects.

Tools

Tool Use for Where to find it


Select-Object Choosing properties, calculating Windows PowerShell
new properties, and choosing the
first or last few objects from a list
of objects

Sort-Object Reordering objects according to Windows PowerShell


the collation order of certain
properties

Format-Wide Presenting one property of a list Windows PowerShell


of objects in a specific number of
columns

Format-List Presenting many properties of a Windows PowerShell


list of objects with one property
per line

Format-Table Presenting a list of objects in Windows PowerShell


tabular format with different
properties in each column and an
object per line
Introduction to Scripting with Windows PowerShell™ 5-1

Module 5
Introduction to Scripting with Windows
PowerShell™
Contents:
Lesson 1: Writing Windows PowerShell Scripts 5-3
Lesson 2: Script Parameters 5-10
Lesson 3: Security in Windows PowerShell 5-16
Lesson 4: Customizing Windows PowerShell with Profiles 5-20
Lab: Implementing Scripts in Windows PowerShell 5-25
5-2 Introduction to Scripting with Windows PowerShell™

Module Overview

Some system administration can be performed interactively with Windows


PowerShell. Script writing techniques are vital for automating tasks using
Windows PowerShell.
This module explains how to write and modify basic scripts to perform a sequence
of cmdlets. Security and working with credentials are also discussed. You will use
many of the foundations provided in this module every time you write a script.
Introduction to Scripting with Windows PowerShell™ 5-3

Lesson 1
Writing Windows PowerShell Scripts

A script is a sequence of commands and Windows PowerShell cmdlets. Scripts can


use pipelines, expressions, variable assignments, and other language constructs.
This lesson introduces scripting with Windows PowerShell and presents basic
guidelines for writing Windows PowerShell scripts.
5-4 Introduction to Scripting with Windows PowerShell™

What Is a Script?

Key Points
A Windows PowerShell script is a sequence of Windows PowerShell statements
that is saved as a file with a .ps1 extension. You can run a script the same way that
you would run a cmdlet, with or without parameters.
You can run a script from within Windows PowerShell by specifying either its full
or its relative path.

Question: Which statements would you put into a script file?


Introduction to Scripting with Windows PowerShell™ 5-5

Returning Values from a Script

Key Points:
Separate output channels exist for:
• Direct output from the host
• Standard output from a script
The standard output of a script is the value of the script. The value of the script is
made up of a combination of:
• Implicit output values that are displayed in a script
• Values that are explicitly emitted using the Write-Output cmdlet
• The value of the return construct

Question: Can you think of a situation where you would need to write an object to
a pipeline?
5-6 Introduction to Scripting with Windows PowerShell™

Demonstration: Returning Values

Question: What is the difference between Write-Output and Write-Host?


Introduction to Scripting with Windows PowerShell™ 5-7

Demonstration: Trapping Errors

Question: Which Windows PowerShell language construct is used to catch errors


by registering an error handler?

Additional Reading:
For more information on converting VBScript to Windows PowerShell, see:
• Converting VBScript Commands to Windows PowerShell Commands
• VBScript to Windows PowerShell: Converting VBScript's On Error Statement
5-8 Introduction to Scripting with Windows PowerShell™

What Is Scope?

Key Points
A scope is the context in which a variable or function is defined. Some examples of
different scopes are:
• Global
• Script
• Function

Variables and functions are normally defined in the current scope. Nested code
blocks within a script define an inner scope.
Question: When would you need to use nested code blocks?
Introduction to Scripting with Windows PowerShell™ 5-9

Demonstration: Scope of Definitions

Question: How do you define a variable as Global scope?


5-10 Introduction to Scripting with Windows PowerShell™

Lesson 2
Script Parameters

Scripts can accept input via a pipeline or redirection, but they can also be invoked
with parameters. Using parameters with a script allows additional data to be
passed to the script in a structured way. This lesson provides a basic introduction
to the declaration and use of parameters in Windows PowerShell scripts.
Introduction to Scripting with Windows PowerShell™ 5-11

Two Kinds of Script Parameters

Key Points
Scripts can take parameters, just like cmdlets can.
The special variable $args refers to the arguments that are passed to a script. The
count method can be used on the $args variable such that $args.count is the
number of arguments that have been passed to the script when it is invoked.
The value of $args can be a System.Object[] (an array of objects or collection);
therefore, simply referring to $args might not yield an expected result.
You can index this $args array by number to access each argument. Similar to
parameters on a cmdlet, the script can process these arguments to change its
behavior.
You can use basic operators, such as the foreach construct or the ForEach-Object
cmdlet, to iterate through arguments.

Question: Which type of comments are useful to include in a script?


5-12 Introduction to Scripting with Windows PowerShell™

Parameters as an Argument Array

Key Points
The argument array $args is effective for handling one or more parameters that
represent a list of values that the script will process.
A script can use constructs, such as foreach, to process each argument (parameter)
according to the same rules.
For scripts in which there are different positional meanings for each argument (for
example, $args[0] is a folder to search, $args[1] is a maximum size, etc.), using
named parameters can make the script more maintainable.
The $args array can still be used when a parameter block is defined, to access all
the actual parameters beyond the number declared in the parameter block.

Question: What kind of script parameters would be easier to access with the $args
argument array?
Introduction to Scripting with Windows PowerShell™ 5-13

Script Parameters with a Named Parameter Block

Key Points
Parameters can be bound to specific variables rather than $args by declaring these
variables in a parameter block.
The syntax is the param keyword, a parenthesis, and a comma-separated list of
variables followed by a closing parenthesis.
When the script is invoked with positional parameters (that is, no parameter
names provided), the parameter values (arguments) are bound to each variable in
order.
Alternatively, the script can be invoked with named parameters.

Question: What is an advantage of using a named parameter block instead of


simply processing parameters using the argument array?
5-14 Introduction to Scripting with Windows PowerShell™

Demonstration: Script Parameters

Question: What would be an advantage of using an argument array to refer to the


parameters, as opposed to using a named parameter block?
Introduction to Scripting with Windows PowerShell™ 5-15

Demonstration: Using Comments and Line Continuation

Question: Are comments necessary in scripts? Why or why not?


5-16 Introduction to Scripting with Windows PowerShell™

Lesson 3
Security in Windows PowerShell

Administrators should incorporate protection from dangerous scripts into the


scripting environment. Additionally, many administrative tasks require special
administrative credentials in order to accomplish the automation work they were
designed and written to perform. This lesson presents solutions to these aspects of
Windows PowerShell security.
Introduction to Scripting with Windows PowerShell™ 5-17

Execution Policy Security Levels

Key Points
Windows PowerShell includes a security feature that can restrict whether
configuration files can be loaded and whether scripts can be run. You can choose
one of several levels.
Execution policy can be set at the command line (set-execution policy) or specified
via Group Policy.

Use Get-Help about_Signing for more information.

Question: Which security level is appropriate for your tasks?

Additional Reading:
• For a description of how to edit the Zone.Identifier stream of a file using
Notepad, see How does the RemoteSigned execution policy work?
5-18 Introduction to Scripting with Windows PowerShell™

Signing Scripts

Key Points
If you have a public key code signing certificate, you can use the
Set-AuthenticodeSignature cmdlet to sign Windows PowerShell scripts.
Signed scripts can be used on the local computer if the certificate is trusted locally.
A self-signed certificate is sufficient for such purposes.
Signed scripts can be used on any computers on the network that trust the signing
certificate.

Use Get-Help about_Signing for more details.

Question: Which cmdlet is used to sign script files?


Introduction to Scripting with Windows PowerShell™ 5-19

Working with Credentials

Key Points
The Get-Credential cmdlet prompts you for a user name and a password using a
Windows dialog box designed for fetching such credentials. You can also pass the
user name (which can include a domain) as a parameter to Get-Credential to
simplify user input.. Get-Credential returns a PSCredential object, which you can
use on other cmdlets, such as Get-WMIObject, to pass credentials. Not all cmdlets
support credentials.

Question: How can credentials be used to access resources on another computer?


5-20 Introduction to Scripting with Windows PowerShell™

Lesson 4
Customizing Windows PowerShell with Profiles

You can use Windows PowerShell scripts to customize the Windows PowerShell
environment. Windows PowerShell supports special scripts called profiles that are
run when Windows PowerShell starts.
Because such profile scripts are run each time that Windows PowerShell starts,
definitions and changes to the environment that you include in these scripts are
persistent across all invocations of Windows PowerShell. This lesson focuses on
profiles.
Introduction to Scripting with Windows PowerShell™ 5-21

What Are Windows PowerShell Profile Files?

Key Points
Windows PowerShell profile files are scripts that Windows PowerShell runs when
it is launched.

Profiles are Windows PowerShell scripts that are a collection of aliases, functions,
and commands. When such scripts prove to be useful, you can include them in the
profile so that they run every time Windows PowerShell is started.

Question: Which scripts would be good to run automatically on


Windows PowerShell?
5-22 Introduction to Scripting with Windows PowerShell™

Demonstration: Customizing Console Colors

Question: How would you make sure that changes to your console environment
(such as colors) will be used the next time that you run Windows PowerShell?
Introduction to Scripting with Windows PowerShell™ 5-23

Scope of Windows PowerShell Profiles

Key Points
There are two paths and two primary variants of profile file names that yield these
paths:

$PSHOME\profile.ps1
$PSHOME\Microsoft.PowerShell_profile.ps1
$HOME\Documents\WindowsPowerShell\profile.ps1
$HOME\ Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

The profile.ps1 files apply for all shells, whereas the


Microsoft.PowerShell_profile.ps1 files apply only to the Microsoft.PowerShell shell.
The files within $PSHOME apply to all users.
The files in $HOME apply only to a single user.

Question: How would you determine which shell you are in?
5-24 Introduction to Scripting with Windows PowerShell™

Demonstration: Adding Common Aliases to the Profile

Key Points
Set-Alias is a cmdlet that you can place in a profile file so that each time Windows
PowerShell launches, the aliases in the profile file will be loaded.

Question: What could you put into a profile file beside aliases?
Introduction to Scripting with Windows PowerShell™ 5-25

Lab: Implementing Scripts in Windows


PowerShell

Exercise 1: Writing and Running a Script


Scenario
Another administrator in Woodgrove Bank needs to regularly generate a report of
running processes that includes specific information. You need to write a script
that will enable the other administrator to perform this task without manually
entering Windows PowerShell commands.

Exercise Overview
In this exercise you will write a Windows PowerShell script that displays specified
information about running processes.
The main tasks for this exercise are as follows:
1. Start the 6434A-NYC-DC1 virtual machine and log on as Administrator.
2. Create an empty script file.
3. Add Windows PowerShell commands to the script.
4. Run the script and verify its operation.
5-26 Introduction to Scripting with Windows PowerShell™

f Task 1: Start the 6434A-NYC-DC1 virtual machine and log on as


Administrator
1. Start 6434A-NYC-DC1 and log on as Administrator using the password
Pa$$w0rd.

f Task 2: Create an empty script file


• Use Windows Explorer to create a new folder named C:\Scripts.
• Use Windows Explorer to create a new text file named Mod5Task2.ps1.

f Task 3: Add Windows PowerShell commands to the script


• Use Windows Notepad to open Mod5Task2.ps1.
• Add the Windows PowerShell command that will display the currently
running processes in a table format, so that only the name, physical memory
utilization, and virtual memory utilization of the process are displayed. The
table columns should not have excess blank space between them.

f Task 4: Run the script and verify its operation


• Run Mod5Task2.ps1 and verify that it displays the desired information,

Results: After this exercise, you should have created a script which, when executed,
displays information about processes running on the server.

Exercise 2: Customizing Profiles


Scenario
You and the other administrators at Woodgrove Bank frequently use Windows
PowerShell to automate Windows Server administrative tasks. You need to become
more efficient at using the shell and must create shorter aliases to some of the
common cmdlets that you run. You want these aliases to be available each time
that you open the shell; therefore, you add them to your Windows PowerShell
profile. When your colleagues see how efficient you are with these aliases, they
might want to use them too, so you will likely be sharing your profile changes with
them.
Introduction to Scripting with Windows PowerShell™ 5-27

Exercise Overview
In this exercise you will create a Windows PowerShell profile and configure it to
automatically create aliases each time that the shell is opened.
The main tasks for this exercise are as follows:
1. Create a blank profile script.
2. Add commands to the profile.
3. Test the profile and verify its operation.

f Task 1: Create a blank profile script


• Use Windows Explorer to create a new, blank Windows PowerShell profile
script that will open only for your user account, and only for the default shell
instance.

f Task 2: Add commands to the profile


• To the profile that you created, add the command that creates an alias named
Gel for the cmdlet Get-EventLog.
• To the profile you created, add the command that creates an alias named Of
for the cmdlet Out-File.

f Task 3: Test the profile and verify its operation


• Close and reopen Windows PowerShell.
• Run Gel Security and ensure that the security event log entries are displayed.
• Run Ps | Of C:\Scripts\Processes.txt and verify that a file named
C:\Scripts\Processes.txt is created, and that the file contains a list of currently
running processes.

Results: After this exercise, you should have created a Windows PowerShell profile
that automatically creates aliases each time the shell is opened.
5-28 Introduction to Scripting with Windows PowerShell™

Lab Review
Introduction to Scripting with Windows PowerShell™ 5-29

Module Review and Takeaways

Review Questions
1. At a Windows PowerShell prompt, what would you type to run a script file
called myscript.ps1 that is in the current folder?
2. How would you define a variable in a script so that its value is usable at the
Windows PowerShell command prompt? For example, assign the variable
$mydocs the value $HOME\Documents.
3. How would you call a script in the current folder called get-payroll.ps1 and
assign the return value of the script to a variable named $pay?
4. How would you change the Windows PowerShell execution security policy
level to allow any local scripts to be run, but require scripts that have been
downloaded to have a digital signature?
5-30 Introduction to Scripting with Windows PowerShell™

Common Issues Related to Writing Scripts


Identify the causes for the following common issues related to writing scripts and
fill in the troubleshooting tips. For answers, refer to relevant lessons in the module.

Issue Troubleshooting tip


When attempting to run a script you
receive an error such as:
"The term 'myscript.ps1' is not
recognized as a cmdlet, function,
operable program, or script file.
Verify the term and try again."

Output from a script appears on the


display without a problem. When
you assign the output of the script to
a variable, the output is not assigned
to the variable but still comes to the
console.

A script will not run and an error


such as the following results.
File: C:\Users\Ellen
Adams\Documents\test1.ps1 cannot
be loaded because the execution of
scripts is disabled on this system.

Real-world Issues and Scenarios


• You manage Web servers at a marketing firm. Two members of your team, Joe
and Ellen, are integrating scripts that you have successfully developed and
used into their site management tools. Your team sets up a private Web site
where you post the scripts that you are sharing. Joe and Ellen download your
scripts and use them in their framework. What recommendations do you have
for script security so that Ellen and Joe can run your scripts successfully?
Introduction to Scripting with Windows PowerShell™ 5-31

Best Practices Related to Writing Scripts


Supplement or modify the following best practices for your own work situations:
• Include comments within scripts that describe the intended use of the script
along with author and revision history. Do this even for scripts that you plan
to use only twice because scripts can evolve and last longer than initially
expected.
• Include plenty of white space within scripts to enhance readability. Use
spaces consistently around parentheses and braces so that the scripts are
easier to understand.
• Use an execution policy of RemoteSigned instead of Unrestricted so that
unsigned downloaded scripts are not run accidentally.

Tools .

Tool Use for Where to find it


Get-ExecutionPolicy Showing the current execution Windows PowerShell
policy security level

Set-ExecutionPolicy Modifying the current execution Windows PowerShell


policy security level; for example
from Restricted to RemoteSigned

Set- Creating a digital signature with Windows PowerShell


AuthenticodeSignature code signing for a Windows
PowerShell script file
5-32 Introduction to Scripting with Windows PowerShell™
Implementing Flow Control and Functions 6-1

Module 6
Implementing Flow Control and Functions
Contents:
Lesson 1: Controlling the Flow of Execution Within Scripts 6-3
Lesson 2: Iteration Flow Control 6-10
Lesson 3: Developing and Using Functions 6-15
Lab: Implementing Functions and Flow Control in Windows PowerShell 6-23
6-2 Implementing Flow Control and Functions

Module Overview

Most scripts use language features to alter the control of execution. If a condition is
true, the script performs one set of operations; if the condition is not true, the
script can perform a different set of actions.
A function is a typically small bit of Windows PowerShell™ scripting code that you
give a name to. You can use functions, for example, to wrap or hide more complex
logic. Functions can be defined in a script or in a profile file.
Judicious use of functions and filters can greatly simplify complex code, reduce the
length of long code, and even make it possible to perform tasks that would have
otherwise been difficult or tedious to script.
This module explains the control statements in Windows PowerShell, looks at how
you can move scripts into functions, and demonstrates how to add functions to
profiles.
Implementing Flow Control and Functions 6-3

Lesson 1
Controlling the Flow of Execution
Within Scripts

Flow control consists of choosing whether or not to run a code block based on a
formula (a logical expression). Logical operators can be used to combine the basic
comparisons to build logical expressions that express your decision-point needs.
A number of flow control constructs are available in Windows PowerShell. You can
use these flow control constructs to write scripts that go beyond the straight
sequence of steps that lack variation or decision points.
6-4 Implementing Flow Control and Functions

What Is an Expression?

Key Points:
Windows PowerShell supports many kinds of expressions such as arithmetic
expressions, string expressions, and logical expressions. Most of the Windows
PowerShell flow control constructs make use of logical expressions.
Logical expressions have the following characteristics:
• They are used to make decisions about which parts of a script to execute.
• Certain flow control constructs, such as if and while, accept a logical
expression.
• Logical expressions can be used to combine comparison expressions.
• Complex logic can be used to write scripts that solve real-world problems.

Question: Can you think of a complex logical expression to use in your work?
Implementing Flow Control and Functions 6-5

Comparison Operators in Expressions

Key Points
There are three major varieties of comparison operators:
• Equality/greater/less: Windows PowerShell uses -eq, -gt, -lt, and -le, -ge, and -
ne for comparisons. These are all binary operators.
• Wildcard/regular expression: The wildcard operators -like and -notlike are
used to match wildcards in strings. Regular expressions are used with the
-match and -notmatch operators.
• Type matching: The type matching operators -is and -isnot enable a value to
be compared against a data type.
The comparison, wildcard, and regular expression operators support case-sensitive
and explicitly case-insensitive forms by interjecting a c or an i, respectively,
between the hyphen and the basic keyword.

Question: Which expression would you use to express whether disk capacity
exceeds 500 megabytes? Assume that the variable $capacity holds the value of the
capacity of the disk in question.
6-6 Implementing Flow Control and Functions

Demonstration: Working with Comparison Operators

Question: Which operator would you use to see if a value is at or beyond a certain
value?
Implementing Flow Control and Functions 6-7

Executing Parts of a Script Using if/else Constructs

Key Points
You can use an if construct to execute a code block if the expression evaluates to
false. Optionally, you can add additional (elseif) conditions and an else condition.
The expression in parentheses after the if keyword is evaluated and checked for
truth or falsity.
• If the expression evaluates to true, the code block immediately after the
expression is run. This first code block is sometimes called the then clause.
For such scenarios, any accompanying else clause would be ignored.
• When the if expression evaluates to false, the implicit then clause is ignored
(skipped), but an accompanying else clause is run. The else clause is simply
an alternate code block.

Question: If the code block on an if construct does not run because the
conditional expression of the if construct evaluates to $false, what will happen
with the code block of a subsequent else?
6-8 Implementing Flow Control and Functions

Using elseif with if/else

Key Points
An elseif clause is functionally the same as an additional if construct inside the
code block of the preceding if construct.
A cascade of if/elseif/elseif/…/else clauses constitute one if construct.
If the conditional expressions of the if and elseif clauses do not use all the same
variables, or if ranges of numbers are checked, then an if/elseif/else construct has
an advantage over a switch construct.

Use Get-Help about_if for more information on this topic.

Question: Do the variables that are used in the conditional expression of the if
clause need to be the same variables that are used in the conditional expressions of
the elseif clauses?
Implementing Flow Control and Functions 6-9

Flow of Execution Based on the switch Construct

Key Points
A script comparing the same variable with different values in a sequence of
if/elseif constructs can be:
• Tedious to write
• Prone to error
• Difficult to read

The compact switch construct offers a powerful alternative to if/elseif constructs.


The use of wildcards or regular expressions makes the switch construct even more
powerful.
By default, without options, switch performs a case-insensitive match.

Question: What would be the benefit, if any, of writing a sequence of conditional


code blocks using the switch construct as opposed to using a cascade of if, else/if,
else constructs?
6-10 Implementing Flow Control and Functions

Lesson 2
Iteration Flow Control

Iteration involves looking at a collection of objects one at a time. The ForEach-


Object cmdlet in Windows PowerShell enables you to iterate through objects in a
pipeline and objects in an array.
Windows PowerShell also provides additional constructs for iteration flow control
that are similar to the flow control mechanisms that you might have seen in other
programming languages.
This lesson presents the for and while constructs along with a discussion of break,
continue, and return in the context of flow control constructs.
Implementing Flow Control and Functions 6-11

Demonstration: Review of Foreach-Object

Question: How are the foreach construct and the ForEach-Object cmdlet similar?
How are they different?

Question: What type of data does each iterate through?


6-12 Implementing Flow Control and Functions

Basic Iteration Constructs

Key Points
Windows PowerShell supports three forms of basic iteration construct that are
simpler than the for construct:
• while: The while construct has a conditional expression and a code block.
There is no initializer clause or repeat/between clause the way there is in the
for construct.
• do/while: The do/while construct has the keyword do prior to the code block,
and the while keyword and conditional expression following the code block.
The condition is checked at the end.
• do/until: The do/until construct is essentially the same as the do/while
construct with the sense of the conditional inverted.

Question: Can you think of scenarios at your workplace when you would use one
of these constructs?
Implementing Flow Control and Functions 6-13

Iterating in General Using the for Construct

Key Points
The for construct has four main elements. Three of these elements (the initializer,
condition, and repeat clauses) are within the parentheses separated by semicolons
(all the semicolons are optional). The fourth part is the code block, which
comprises the processing in the body of the loop.
The initializer, condition, and repeat/between clauses can be simple or complex
expressions.
The for construct is a classic language construct that can be used in cases where
neither the foreach construct, nor the ForEach-Object cmdlet are appropriate.

Question: When would you use the for construct instead of a foreach construct?
6-14 Implementing Flow Control and Functions

Demonstration: Controlling Flow with while, do while,


and do until

Question: Can you think of a situation where the for construct would be more
useful than the while construct?
Implementing Flow Control and Functions 6-15

Lesson 3
Developing and Using Functions

Windows PowerShell also supports a construct called a function, and a variant of


this, called filter. Fundamentally, functions resemble named code blocks in that
they can handle parameters and have their own scope. They are defined much the
same way as variables or aliases. A script or profile can define one or more
functions and their definitions remain defined in the local or global scope
(depending on the scope used in the function definition) as long as that scope
exists.
Functions, and their specialized form, filters, are an essential building block for
automation. This lesson discusses the fundamentals of functions and filters.
6-16 Implementing Flow Control and Functions

What Is a Function?

Key Points
A function is a definition of a code block with a name. Functions are, therefore,
similar to scripts, but they can be loaded in random access memory (RAM) after
they are defined. One or more functions can be defined within a script.
Functions can support arguments, but the arguments can be declared, typed, and
initialized.
The scope of functions is identical to the scope of variables. A function that is
defined inside another function or another script is lost when that script or
function completes execution.

Question: How is a function different from a script?


Implementing Flow Control and Functions 6-17

Filters vs. Functions

Key Points
A filter is a function that either is declared with the filter keyword (instead of
function) or has a PROCESS block defined.
Filters can have three code blocks defined:
• BEGIN
• PROCESS
• END

Functions wait for all input coming down the pipeline to be accumulated before
they begin processing. The $input variable is used to process all input.

Question: How is a filter different from a function?


6-18 Implementing Flow Control and Functions

Styles of Function Parameters

Key Points
Function and filter parameters are loosely bound. Use the $args array and
$args.count to address them.
You can name parameters. You can declare parameters with specific data types.
You can initialize default values for parameters so that if a caller does not supply a
certain parameter, a default value is assumed.

Question: What is the benefit of using named parameters?

Additional Reading:
For more information about using parameters in Windows PowerShell, see
Windows PowerShell: Next Generation Command Line Scripting by Jeffrey Snover.
Implementing Flow Control and Functions 6-19

Demonstration: Positional vs. Named Parameters

Question: When would you use named parameters instead of positional


parameters?
6-20 Implementing Flow Control and Functions

The Dot Operator

Key Points
The unary dot (.) operator is used to run a script in the local scope rather than in a
nested script scope. This technique is called "dot sourcing" the script.
Ensure that there is a space between the dot and the path to the script. The space is
critical punctuation after the dot operator.

Note: The four Windows PowerShell profiles are run using the dot sourcing construct.
This approach makes the results available in your shell when the profile scripts have
completed.

Use Get-Help about_Scope for more information on this topic.

Question: When would you need to run a script in the local scope?
Implementing Flow Control and Functions 6-21

Demonstration: Dot Sourcing

Question: In the current environment, how would you declare variable and
function definitions that are not defined with global scope in a script?
6-22 Implementing Flow Control and Functions

Loading Functions into a Script or Profile

Key Points
Functions and filters are defined in script files, including profile files. After these
functions are loaded, if they are global in scope, they can subsequently be used
outside the script.
Define the function in global scope (for example, function global:Get-BigProcess)
so that when the script is completed, the function is still defined.

Question: How would you save a recent sequence of commands from history to a
persistent function?

Question: How would you take commands that you have recently executed
interactively in Windows PowerShell and save them to a file that can then be
turned into a script?
Implementing Flow Control and Functions 6-23

Lab: Implementing Functions and Flow Control


in Windows PowerShell

Exercise 1: Adding Flow Control in a Script


Scenario
You are a network administrator for Woodgrove Bank. You need to use Windows
PowerShell to inventory operating system versions, including the version of the
latest installed service pack, from several computers. You decide to use information
that is available via Windows Management Instrumentation (WMI) and choose the
Win32_OperatingSystem class to retrieve this information. Because the Caption
property of this class provides a more verbose operating system product name
than you want to display, you choose to use Windows PowerShell flow control to
help translate the operating system build number into a short representation of the
operating system version.

Exercise Overview
In this exercise, you will control the flow of processing of script code blocks.
The main tasks for this exercise are as follows:
1. Start the 6434A-NYC-DC1 virtual machine, log on as Administrator, and start
Windows PowerShell.
6-24 Implementing Flow Control and Functions

2. Retrieve the Windows build number and service pack version from a
computer.
3. Write a script that uses the build number to display the operating system
version.

f Task 1: Start the 6434A-NYC-DC1 virtual machine, log on as


Administrator, and start Windows PowerShell
• 1. Start 6434A-NYC-DC1, log on as Administrator using the password
Pa$$w0rd, and start Windows PowerShell.

f Task 2: Retrieve the Windows build number and service pack version
from a computer
• Use the Get-WmiObject cmdlet to retrieve the Win32_OperatingSystem class
from 6434A-NYC-DC1
• Store the retrieved class in a variable.
• Use the -computerName parameter of Get-WmiObject to specify NYC-DC1 as
the computer name.
• Use the variable containing the retrieved class to display the BuildNumber
and ServicePackMajorVersion properties.

f Task 3: Write a script that uses the build number to display the
operating system version
• Create a new, blank script named Mod6Task3.ps1.
• To the script, add commands that accomplish the following tasks:
• Store the computer name NYC-DC1 into a variable named $computer.
• Use Get-WmiObject to retrieve the Win32_OperatingSystem class from
the computer name stored in $computer. Store the retrieved class in a
variable named $os.
• Store "0" in a variable named $osver.
• Use a switch construct to examine the BuildNumber property of the $os
variable. Store a short version of the operating system version in the
variable $osver, according to the following rules:
Implementing Flow Control and Functions 6-25

• If the build number is 2195, store "Win2000" in $osver.


• If the build number is 2600, store "WinXP" in $osver.
• If the build number is 3790, store "Win2003" in $osver.
• If the build number is 6000, store "Vista" in $osver.
• Otherwise, store "Win2008" in $osver.
• Display output similar to this:
NYC-DC1: Win2008 SP0
• Run the script named Mod6Task3.ps1.

Results: After this exercise, you should have created a script that retrieves and displays
the operating system version and latest installed service pack version from a specified
computer.

Exercise 2: Creating Functions


Scenario
You are an administrator for Woodgrove Bank. You have written a script that
retrieves the Windows operating system name and service pack version number
from a remote computer. However, you need to perform this task frequently, so
you want to make the script more easily accessible from within Windows
PowerShell. You decide to convert your script to a function and define this
function in your Windows PowerShell profile so that it does not need be defined
for each new instance of Windows PowerShell.

Exercise Overview
In this exercise, you will create a function and add it to their profile.
The main tasks for this exercise are as follows:
1. Rewrite Mod6Task3.ps1 as a function.
2. Add the function to your Windows PowerShell profile.

f Task 1: Rewrite Mod6Task3.ps1 as a function


• Copy Mod6Task3.ps1 to Mod6Function.ps1.
• Modify Mod6Function.ps1 so that the code is contained within a function
named Get-OSVersion.
6-26 Implementing Flow Control and Functions

• The function should accept one input argument named $computer.


• The contents of the function should use the $computer input argument
rather than the $computer variable previously defined in the script.
• The function should return its output rather than writing it to the console
window.
• After defining the function, add the command Get-OSVersion NYC-DC1 to
the script.
• Run Mod6Function.ps1 and verify its output.

f Task 2: Add the function to your Windows PowerShell profile


• Add the Get-OSVersion function to your Windows PowerShell profile.
• Close and re-open Windows PowerShell, and run Get-OSVersion NYC-DC1 to
verify the availability of the function.

Results: After this exercise, you should have created the Get-OSVersion function and
added it to your profile.
Implementing Flow Control and Functions 6-27

Lab Review
6-28 Implementing Flow Control and Functions

Module Review and Takeaways

Review Questions
1. What are the four parts of a for construct besides the for keyword and
punctuation?
2. What is the advantage of using a switch construct instead of a cascade of
if/elseif/else?
3. What is the difference between the while and do/while constructs?
4. What is the difference between the do/while and do/until constructs?
5. Which elements does a filter have that a function does not?
Implementing Flow Control and Functions 6-29

Common Issues Related to Functions and Scripts


Identify the causes for the following common issues related to functions and
scripts and fill in the troubleshooting tips. For answers, refer to relevant lessons in
the module.

Issue Troubleshooting tip


You get an infinite loop. A script or
function runs and never exits; it
must be forcibly cancelled.

After a script runs, the functions that


it defines are not available in the
shell.

A function or script does not use the


parameters correctly; they appear to
be mixed up.

Real-world Issues and Scenarios


1. You have several Windows PowerShell scripts that you and your colleagues
have developed in-house. Now you install a package of scripts that you have
purchased or acquired for monitoring disk, folder, and network share usage
on your servers and workstations. Over the next few weeks you notice that
some of your scripts are not working correctly. One example is a function
called Update-Statistics that your organization developed and uses for
tracking Web site and blog updates and access. Upon investigation, you find
that the disk monitoring package that you downloaded also has a function
called Update-Statistics, which is used internally but defined with global
scope.

2. Based on your scripting experience with Windows PowerShell, you are


promoted to a position in which you are now responsible for automating
enterprise trouble ticketing and event log correlation. Much work has already
been done on this automation project by your predecessor and your new
colleagues. In your new role, you are expected to be able to:
• Utilize existing scripts, functions, and filters that have been developed
by the team
• When necessary, be able to modify some scripts and write new
modules (scripts, functions, filters) within the existing framework.
6-30 Implementing Flow Control and Functions

Best Practices Related to Flow Control and Functions


Supplement or modify the following best practices for your own work situations:
• Use a switch construct when a sequence of if/elseif/else constructs uses the
same input expression (for example, variable). Over the life of many scripts
and functions, the switch construct is often more manageable for readability
and maintainability. Furthermore, the array processing and wildcard or regular
expression matching capabilities of the switch construct are very powerful.
• Think modularly when you are writing scripts. Although not as rigorous as
large-scale software development, script writing can benefit from at least a few
moments of thoughtful design. If you find that scripts are doing too many
things, consider breaking different parts into functions. When this process is
performed logically, there can be many benefits. Also, if you realize that an
initial version of a script fetches data, processes the data, and formats the
output, consider defining a filter (or more than one) to handle the core part of
the processing. Then use a pipeline to fetch the data and send it to the filter.
You can also code fetching and filtering the pipeline in a function. In this way,
the overall operation can use the function that runs the whole process in a
pipeline; or if you want only the filtering part and a different way of getting the
input data, the filter is also available. This sort of thinking in terms of division
of labor and modularity can greatly reduce tweaking and redevelopment time
over the lifetime of scripts.
• Always be cognizant of scope of definitions. Variables, functions, and filters are
normally defined within the local scope. Private scope can be used when it is
explicitly required. Global, script, local, and private scopes all have their
purpose, but they can be misused. Avoid the temptation to define all variables,
functions, and filters with global scope when it is not necessary. Judiciously
choosing the appropriate scope for such definitions can reduce the possibility
of conflicts with other software and scripts, allow greater effectiveness in
modularity, and reduce clutter of the shell environment with definitions that
could have been localized.
• Use parameterized functions and filters when you must supply control values
for the behavior of the function or filter other than the input data. When
required, typed parameters or default values can be specified. Use of these
technologies and techniques can leverage the abilities of Windows PowerShell
and help you focus on the automation requirements of your scripts.
Implementing Flow Control and Functions 6-31

Tools
Most of the tools listed in this module are Windows PowerShell language
constructs that are used for flow control. A notable exception is the ForEach-Object
cmdlet. These constructs are included here for quick reference.

Tool Use for Where to find it


ForEach-Object cmdlet Looping through pipeline input Windows PowerShell

foreach construct Looping through array elements Windows PowerShell

for construct General looping Windows PowerShell

while construct General looping similar to for Windows PowerShell


without initializer and repeat
portions

do/while and do/until General looping similar to while Windows PowerShell


constructs with condition checked at end of
loop rather than beginning

break construct Exiting a loop (foreach, for, Windows PowerShell


while, do) or switch

continue construct Skipping remainder of loop body Windows PowerShell


and continuing with next iteration

throw construct Generating an exception that is Windows PowerShell


either handled by a defined trap
handler or the built-in exception
handler

return construct Exiting the current function, filter, Windows PowerShell


or script; the return construct can
accept a value to emit as output
from the function or script

if, elseif, else Selecting code blocks based on Windows PowerShell


constructs conditional expressions

switch construct Selecting code blocks based on a Windows PowerShell


common input value and an
assortment of matching values

function construct Encapsulating a code block with Windows PowerShell


defined parameters and a name;
6-32 Implementing Flow Control and Functions

Tool Use for Where to find it


functions have their own scope
and can have a hierarchy of
internal flow control and nested
code blocks.

filter construct Processing pipeline input with Windows PowerShell


beginning, middle, and end
phases; filters are specialized
functions; a filter can be explicitly
declared as being a filter, but any
function with BEGIN, PROCESS, or
END code blocks is implicitly a
filter.
Working with Files, the Registry, and Certificate Stores 7-1

Module 7
Working with Files, the Registry, and Certificate
Stores
Contents:
Lesson 1: Using Data Stores 7-3
Lesson 2: Using Providers 7-10
Lesson 3: Filtering and Selecting with Regular Expressions 7-15
Lesson 4: Implementing Event Log Management 7-20
Lesson 5: Persisting Objects in Files 7-23
Lab: Working with Files, the Registry, and Certificate Stores 7-30
7-2 Working with Files, the Registry, and Certificate Stores

Module Overview

Most administrators regularly work with a variety of data stores, including the file
system and the registry, directly. By using Windows PowerShell™ providers, you
can use many of the same cmdlets for managing and accessing both the registry
and the file system, and other data stores.
This module explains how to access data stores, the file store, the registry,
certificate stores, and other stores. The module also shows you how you can use
wildcards and regular expressions, and how you can import and export aliases and
objects.
Working with Files, the Registry, and Certificate Stores 7-3

Lesson 1
Using Data Stores

Many automation activities call for accessing files, the registry, or other stored
information.
This lesson presents the basic cmdlets that provide access to information stores,
including the file system. The focus is on the concepts of location, items, item
properties, child items, and content access, as well as an introduction to the
cmdlets that are available for working with information stores based on these
concepts.
7-4 Working with Files, the Registry, and Certificate Stores

Using Providers and *-PSDrive Cmdlets

Key Points
You can access the file systems, registry hives, certificate store, and other stores
through Windows PowerShell "drives" (PSDrive).
Each PSDrive depends on a Windows PowerShell provider (PSProvider). Some
providers can support several PSDrives.
The PSProviders are implemented in Windows PowerShell snap-ins (PSSnapin).
Each snap-in can also implement cmdlets and other subsystems and functionality
within the Windows PowerShell environment. Not all PSSnapins implement
providers.
Use of these PSDrive, PSProvider, and PSSnapIn components is an integral part of
the Windows PowerShell provider architecture. The object manager uses these
providers to allow common cmdlets to be used with multiple data stores.

Question: How would you describe or draw the relationship between PSDrive,
PSProvider, and PSSnapin objects?
Working with Files, the Registry, and Certificate Stores 7-5

Introduction to the *-PSDrive Cmdlets

Key Points
Get-PSDrive shows the list of current Windows PowerShell drives.
New-PSDrive creates another Windows PowerShell drive using an existing
provider.
Remove-PSDrive can be used to delete a Windows PowerShell drive.
PSDrives are different from Windows volumes (drives). Creating a new PSDrive
does not create an underlying storage volume in Windows operating systems.
Removing a PSDrive does not delete any underlying storage volumes.

Question: When would you need to delete a Windows PowerShell drive?


7-6 Working with Files, the Registry, and Certificate Stores

Accessing Data Stores

Key Points
Windows PowerShell comes with built-in providers that enable generic access to
several kinds of data stores using generic cmdlets.
You can extend the set of providers to allow access to other types of data stores by
obtaining third-party providers or developing your own.

Question: What are some similarities between file systems, the registry, and
certificate stores?

Question: Can you think of other information stores in Windows® operating


systems that also have similarities to these?
Working with Files, the Registry, and Certificate Stores 7-7

Cmdlets for Item Management

Key Points
Use Get-Command *Item to see the cmdlets that deal with items.
Use Get-Alias | ? { $_.Definition -like ‘*item’ } to show the aliases that translate to
cmdlets ending in "item."
Use Get-Command *Item* (note the * before and after "item") to see the cmdlets
that deal with items, child items, and item properties.
Use Get-Alias | ? { $_.Definition -like ‘*item*’ } to show the aliases that translate to
cmdlets containing the word "item," such as ChildItem, Item, or ItemProperty.

Question: Which cmdlet would you use to view the cmdlets that allow you to
move a file or files?
7-8 Working with Files, the Registry, and Certificate Stores

Using the Set-Location and Get-ChildItem Cmdlets

Key Points
In some cases, the current location in Windows PowerShell is a point in a
hierarchical information or data store.
The variable $PWD is the current location. The cmdlets Get-Location, Pop-
Location, Push-Location, and Set-Location are used to manage the current location.
The default aliases for these cmdlets are:
• Get-Location: gl, pwd
• Pop-Location: popd
• Push-Location: pushd
• Set-Location: sl, cd, chdir

Question: Can you think of a situation in which you might use Push-Location and
Pop-Location?
Working with Files, the Registry, and Certificate Stores 7-9

Accessing the File Store

Key Points
The Get-Content, Add-Content, Clear-Content, and Set-Content cmdlets work with
the contents of items (such as files). Predefined aliases and functions of these
cmdlets are:
• Get-Content (gc, cat, type): Displays the content on the console, or pipes it to a
variable, as an array of strings
• Add-Content (ac): Adds content to an existing or new file
• Clear-Content (clc): Removes all content in a file
• Set-Content (sc): Creates the contents of a file (equivalent to Clear-Content
followed by Add-Content)

Question: How would you read the contents of a file into a variable?
7-10 Working with Files, the Registry, and Certificate Stores

Lesson 2
Using Providers

Besides the FileSystem provider, Windows PowerShell version 1.0 comes with
providers for alias, environment, function, registry, variable, and certificate
information stores. These providers enable a common set of cmdlets to provide
access to all of these types of information stores.
If you understand the nature and relationships between Windows PowerShell
snap-ins (PSSnapin), Windows PowerShell drives (PSDrives), and Windows
PowerShell providers (PSProviders), you can increase the flexibility and
capabilities of Windows PowerShell.
This lesson gives some examples of using the *-Location, *-Item, and
*-ItemProperty cmdlets with providers other than the FileSystem provider. Access
to the registry is shown first, followed by some brief information on certificate store
access. Next, this lesson presents an introduction to the *-PSDrive, *-PSProvider,
and *-PSSnapin cmdlets.
Working with Files, the Registry, and Certificate Stores 7-11

Accessing the Registry

Key Points
Keys and values in the registry are accessible with the same cmdlets that are used
for folders and files in a file system.
Two Windows PowerShell drives are used to access the registry:
• HKCU is used to refer to the registry hive HKEY_CURRENT_USER, which is
part of the current user profile.
• HKLM is used to refer to the registry hive HKEY_LOCAL_MACHINE, which is
part of the Windows configuration.

Question: How would you access a key or value in the registry?

Additional Reading:
For more information on accessing the registry, see Navigating Windows
PowerShell.
7-12 Working with Files, the Registry, and Certificate Stores

How to Add Keys to the Registry

Key Points
The registry provider correlates registry keys to Windows PowerShell items.
You can create new keys with the New-Item cmdlet.

Question: Would you prefer to define a function named something like New-
RegistryKey to accomplish this task, or would you simply use the New-Item cmdlet
at a registry location explicitly?
Working with Files, the Registry, and Certificate Stores 7-13

How to Add Values to the Registry

Key Points
You get registry values by using Get-ItemProperty and specifying the key and value
name. You can also change registry values by using the Set-ItemProperty cmdlet.
These cmdlets are used as follows:
• Use Set-Location, or one of its aliases, to navigate to the registry key in which
you want to edit the value.
• Use Get-ItemProperty, or use an alias, to get the value entry at a particular key.
Note that you have to explicitly state the key name ("." is the current location).
• Use Set-ItemProperty to specify a value name and the data value to assign to
this value entry. As with Get-ItemProperty, you need to explicitly provide the
path to the registry key under which the value items are to be added or
modified.

Question: How would you change a value in the registry?

Question: Would you use a different technique to create a new registry value or
subkey?
7-14 Working with Files, the Registry, and Certificate Stores

Accessing Certificate Stores

Key Points
Every modern machine that uses the Windows operating system has certificate
stores for handling public key certificates and certificate revocation lists (CRLs).
You can use Windows PowerShell to access the certificate stores on a computer.
The Windows PowerShell certificate provider enables access using familiar cmdlets
such as Set-Location, Get-ChildItem, and Get-Item.

Question: How would you find the validity period for a certificate in a
certificate store?
Working with Files, the Registry, and Certificate Stores 7-15

Lesson 3
Filtering and Selecting with Regular
Expressions

Matching string expressions against patterns is a frequent part of interactive


management, scripting, and automation using Windows PowerShell.
This lesson uses file systems and other providers to show the power of pattern
matching and regular expressions. The core focus of this lesson is regular
expressions, which are more powerful than basic wildcards. Knowing how to use
regular expressions and wildcards can dramatically change the way you approach
scripting and automation.
7-16 Working with Files, the Registry, and Certificate Stores

Reviewing Wildcards for Matching Name and


Value Patterns

Key Points
The asterisk (also called star, splat, character 42) matches zero or more characters,
and is the most popularly known wildcard.
Wildcards have many uses, including, but not limited to, the examples shown here.
Windows PowerShell includes five cmdlets, which work with item paths.
Wildcards can be used with these cmdlets or in many other cmdlets that accept a
Path parameter.

Question: Can you identify a scenario in which you would use each form
of wildcard?
Working with Files, the Registry, and Certificate Stores 7-17

Introduction to Regular Expressions

Key Points
Regular expressions were invented in the 1950s and are more general and
powerful than wildcards. There are some similarities and differences.
You use regular expressions to determine whether a string contains a specified
pattern. With regular expressions, you can also look for beginning and ending
patterns. In this regard, regular expressions behave like wildcard patterns.
With a regular expression, a dot (also called a period, full stop, or .) matches any
single character. It is similar to the ? wildcard.
An asterisk (*) in a regular expression matches zero, one, or more of the preceding
characters in the string that you are testing. Asterisks are very different from
wildcards, although the regular expression dot-star (.*) behaves essentially the
same as the * wildcard.

Question: Can you come up with a regular expression to match all file names that
begin with the letter "m" and end with the letter "s"?
7-18 Working with Files, the Registry, and Certificate Stores

Using Patterns with the –like and –match Operators

Key Points
The -like operator in Windows PowerShell matches values against
wildcard patterns.
The -match operator matches values against regular expressions.
The -notlike and -notmatch operators match strings that do not match the
specified patterns.

Question: What would you use either the -like or -match operators to accomplish?
Working with Files, the Registry, and Certificate Stores 7-19

Demonstration: Building Control Flow Based on Wildcard


and Regular Expression Operators

Question: Can you think of an application for the switch Regex option?
7-20 Working with Files, the Registry, and Certificate Stores

Lesson 4
Implementing Event Log Management

Event log management and access are common administrative activities for many
Windows administrators. Automating access to the configuration and content of
event logs is discussed in this lesson.
Working with Files, the Registry, and Certificate Stores 7-21

Accessing an Event Log

Key Points
The Get-EventLog cmdlet provides access to the event logs:
• Get-EventLog -List provides a list of the logs on the current computer.
• Get-EventLog -List -asString shows a simple list of event log names.
• Get-EventLog System -Newest 10 retrieves the newest 10 events from the
System event log.

Question: Why do you need an easy way to access event logs?


7-22 Working with Files, the Registry, and Certificate Stores

Demonstration: Filtering Event Log Results Using


Where-Object and Regular Expressions

Question: What are the properties of an event log entry?

Question: Which of these properties are you most likely to use for filtering events?
Working with Files, the Registry, and Certificate Stores 7-23

Lesson 5
Persisting Objects in Files

Many automation techniques and strategies are based on the ability to save the
objects in files and later use this information as the basis for new objects.
This lesson covers the basics of moving objects in and out of files in Windows
PowerShell, including use of CSV and XML file formats.
7-24 Working with Files, the Registry, and Certificate Stores

Exporting and Importing Aliases

Key Points
The New-Alias, Set-Alias, and Get-Alias cmdlets manage the aliases that are defined
in the current Windows PowerShell session. Aliases can be defined in a profile or
other script for persistence.
You can export sets of aliases to files using the Export-Alias cmdlet. You can import
alias files into the current Windows PowerShell session using the Import-Alias
cmdlet.
You can use this feature to create a company-wide or department-wide set of aliases
that you import using a profile file.

Question: Which strategy is better: to import aliases that you use often or to define
them one by one in a profile file?
Working with Files, the Registry, and Certificate Stores 7-25

Saving and Exporting Objects Using CSV and


HTML Formats

Key Points
The Export-Csv cmdlet exports objects into a CSV file. The Import-Csv cmdlet
imports objects from a CSV file.
The aliases for these cmdlets are:
• Export-Csv: epcsv
• Import-Csv: ipcsv

These cmdlets are useful for interfacing with spreadsheets and databases that
handle CSV formatted files.

Question: Are there any drawbacks of using CSV format for exporting objects?

Question: If so, what are these drawbacks, and which other alternative methods
for exporting objects are available?
7-26 Working with Files, the Registry, and Certificate Stores

Saving and Exporting Objects Using CLiXML Format

Key Points
You can use the Export-Clixml cmdlet to export objects in an XML schema that is
specific to Windows PowerShell.
The CLiXML format is a command-line interface (CLI) XML schema that is used by
Windows PowerShell to include member type information and data type
information about the properties of the exported objects.

Question: Does the CLiXML format have any advantages over CSV format for
exporting and importing objects in Windows PowerShell?

Question: What are the tradeoffs of using each format?


Working with Files, the Registry, and Certificate Stores 7-27

Demonstration: Out-File, Export-CSV, and Export-Clixml

Question: Which cmdlet is the best choice for retaining the closest match to the
original objects when exporting data to a file: Out-File, Export-CSV, or Export-
Clixml?
7-28 Working with Files, the Registry, and Certificate Stores

Importing Objects from Files

Key Points
Get-Content brings in the data that was written with Out-File.
Import-CSV brings in the data that was written with Export-CSV.
Import-Clixml reads files that were written with Export-Clixml.

Question: Which import mechanism is best suited to your administration tasks?


Working with Files, the Registry, and Certificate Stores 7-29

Comparing Saved Versions of Objects with


Current Instances

Key Points
Objects can be compared with one another, property by property, by using
comparison operators such as -eq, -gt, and -lt.
Objects can be compared using the Compare-Object cmdlet.
Values that have been saved can be compared by importing them, then comparing
them. The differences between a live object and one that has been exported and
then imported make it problematic to use Compare-Object with imported objects.

Question: How would you write a script to scan a folder for changes since the
previous time the script ran?

Additional Reading:
For a basic example of Compare-Object, see What Can I Do with
Windows PowerShell?
7-30 Working with Files, the Registry, and Certificate Stores

Lab: Working with Files, the Registry, and


Certificate Stores

Exercise 1: Searching for Certain Files


Scenario
You are an administrator for Woodgrove Bank. Another administrator has asked
you to locate several files on a server, and you have decided to use Windows
PowerShell to accomplish the task. You also need to locate all files containing a
specific text string. This text string is a copyrighted phrase which must be reviewed
and potentially changed by other users.

Exercise Overview
In this exercise, you will search within a folder for all files of a certain type, for files
having a certain name, and for files that contain a particular text string that
represents the trademarked name of a product.
Working with Files, the Registry, and Certificate Stores 7-31

The main tasks for this exercise are as follows:


1. Start the 6434A-NYC-DC1 virtual machine and log on as Administrator.
2. List all XML files residing in the C:\Windows folder.
3. Locate a particular file residing in the C:\Program Files folder.
4. Locate all text files containing a particular text string.

f Task 1: Start the 6434A-NYC-DC1 virtual machine and log on as


Administrator
1. Start 6434A-NYC-DC1 and log on as Administrator using the password
Pa$$w0rd.

f Task 2: List all XML files residing in the C:\Windows folder


• Open Windows PowerShell and change to the C:\Windows folder.
• List all files having the file name extension "xml."

f Task 3: Locate a particular file residing in the C:\Program Files folder


• In Windows PowerShell, change to the C:\Program Files folder.
• Locate all copies of the file named Oledb32.dll.

f Task 4: Locate all text files containing a particular text string


• Change to the C:\Windows\System32\WindowsPowerShell folder.
• Write a script or command that displays the full path and name of all files in
the folder having the file name extension "txt". For files that contain the word
"PowerShell," also display the line number where the word "PowerShell" can be
found within that file.

Results: After this exercise, you should have located files of a specified file type, or files
having a specified name. You should also have located all files containing a specified
trademarked term.
7-32 Working with Files, the Registry, and Certificate Stores

Exercise 2: Modifying Registry Entries


Scenario
A new IT security policy at Woodgrove Bank requires that certain kinds of scripts
be code signed. As an administrator at the bank, you decide to reconfigure the
Windows Script Host (WSH) not to use software restriction policies to determine if
a script is trusted for execution. For greater security you will also configure the
WSH to execute only those scripts that carry a digital signature.

Exercise Overview
In this exercise, you will modify a set of registry entries, changing the TrustPolicy
settings for Windows Script Host.
The main tasks for this exercise are as follows:
1. Modify the WinSAFER registry setting for WSH
2. Create the TrustPolicy setting for the WSH

f Task 1: Modify the WinSAFER registry setting for WSH


• In Windows PowerShell, navigate to the
\HKEY_LOCAL_MACHINE\Software\Microsoft\Windows Script Host
registry key.
• Modify the UseWinSAFER setting to have a value of 0.

f Task 2: Create the TrustPolicy setting for the WSH


• In Windows PowerShell, navigate to the
\HKEY_LOCAL_MACHINE\Software\Microsoft\Windows Script Host
registry key.
• Create a new setting called TrustPolicy and set it to have a decimal value of 2.

Results: After this exercise, you should have modified the WSH registry settings so that
only scripts that are digitally signed will be executed, regardless of the Software
Restriction Policies settings.
Working with Files, the Registry, and Certificate Stores 7-33

Exercise 3: Generating Reports


Scenario
Some of the servers that you administer at Woodgrove Bank are file servers that
have been used to store collections of bitmap files, which is against corporate
policy. You also want to scan for any large files except for dynamically linked
libraries. As a result, you have decided to produce various reports designed to help
clean up the file system of a server. You need to produce a report listing files of a
disallowed type and a report listing files whose size is greater than a specified
amount.

Exercise Overview
In this exercise, you will generate a report of disallowed files on a server, and of
large files on a server.
The main tasks for this exercise are as follows:
1. Produce a report showing disallowed files
2. Produce a report showing large files

f Task 1: Produce a report showing disallowed files


• Use Windows PowerShell to produce a report that shows the location of all
files that have a "bmp" file name extension.
• The report should be in CSV format and should contain two columns that
show the directory path and file name of each file.
• Name the report file Bitmaps.csv.

f Task 2: Produce a report showing large files


• Use Windows PowerShell to produce a report that shows the location and size
of all files with a file size greater than 10 MB.
• The report should exclude files with the file name extension "dll."
• The report should be in CSV format, and contain three columns that show the
directory path, file name, and size in bytes of each file.
• Name the report file BigFiles.csv.
7-34 Working with Files, the Registry, and Certificate Stores

Results: After this exercise, you should have produced two reports that can be used to
help clean up the file system of a server.

Exercise 4: Generating Reports on the Security Log


Scenario
A security auditor working for Woodgrove Bank asks you to provide a report, in
CSV format, of specified security audit events from a server. Knowing that
Windows PowerShell can be used to select the appropriate information, you use
the shell to first retrieve the required security audit events, and then, after you have
manually confirmed that the proper events have been selected, you export the
selected event information to a comma separated values (CSV) file.

Exercise Overview
In this exercise, you will scan the system event log for all instances of a particular
event ID and generate a CSV file containing the results.
The main tasks for this exercise are as follows:
1. Retrieve audit events that match the specified criteria
2. Create a report using the retrieved audit events

f Task 1: Retrieve audit events that match the specified criteria


• Retrieve and display the security event log events having an event ID of 4634,
4672, or 4624.

f Task 2: Create a report using the retrieved audit events


• Using the command created for Task 1, create a CSV file containing the event
ID, entry type, and time generated properties for each audit event.
• Name the CSV file AuditLog.csv.

Results: After this exercise, you should have created a CSV report containing the
specified audit events.
Working with Files, the Registry, and Certificate Stores 7-35

Exercise 5: Comparing Files


Scenario
You are responsible for maintaining a Windows Server 2008 computer. You need
to document the services that are installed on the computer. Periodically, you need
to compare the services that are currently-installed on your computer to the
documented set of services and report any differences.

Exercise Overview
In this exercise, you will create a baseline of installed services on a computer. You
will then install new services, and demonstrate how the baseline can be used to
audit the current configuration of the server and display discrepancies.
The main tasks for this exercise are as follows:
1. Create a baseline of installed services
2. Install additional services on the computer
3. Compare the baseline to the current state

f Task 1: Create a baseline of installed services


• Create an XML file that contains a snapshot of the services that are currently
installed on the computer.

f Task 2: Install additional services on the computer


• Start Server Manager.
• Add the Fax Server role and any required features.

f Task 3: Compare the baseline to the current state


• Compare the snapshot created in Task 1 to the services that are currently
installed on the computer, and display any differences.
• Display the names of only those services that are different.

Results: After this exercise, you should have created a baseline configuration file and
used it to audit the services that are installed on a server.
7-36 Working with Files, the Registry, and Certificate Stores

Lab Review
Working with Files, the Registry, and Certificate Stores 7-37

Module Review and Takeaways

Review Questions
1. Which cmdlet would you use to find the list of files in a folder, similar to the
DOS (and Windows Command Prompt) dir command or UNIX ls command?
2. Which cmdlet is used to change directories, similar to the cd command used
in DOS, Windows Command Prompt, and UNIX?
Answer: The Set-Location cmdlet is similar to the cd command in other
environments. In fact, Windows PowerShell comes with default aliases of cd,
chdir, and sl for Set-Location.
3. Which cmdlet would you use to find the Windows PowerShell drives that are
currently available?
4. What are the four forms of wildcards supported in Windows PowerShell?
5. Which regular expression is the equivalent of the wildcard *?
6. Which cmdlet is used to obtain access to event log content and configuration?
7. Which of the cmdlets for exporting objects retains the most information about
the objects? In other words, which of the export cmdlets is the least lossy?
7-38 Working with Files, the Registry, and Certificate Stores

Common Issues Related to Importing and Exporting Files


Identify the causes for the following common issues related to importing and
exporting files and fill in the troubleshooting tips. For answers, refer to relevant
lessons in the module.

Issue Troubleshooting tip


When you use the Compare-Object
cmdlet to determine how the
configuration of the status of a
subsystem has changed, the
differences between the objects are
not correctly reported. In particular,
the differences between a live object
and one that has been exported and
then imported indicate that (nearly)
everything has changed, when this is
not truly the case.

Real-world Issues and Scenarios


1. Assume that you have saved aliases in either a CSV or Script format. How
would you bring these aliases back into a new Windows PowerShell session?

Best Practices related to file, registry, event log, and certificate


processing
Supplement or modify the following best practices for your own work situations:
• Use the Get-Content cmdlet to obtain the contents of a file or files for
processing. Use pipelines, flow control, and string manipulation as
appropriate to work with the contents. Use the [XML] accelerator to access
configuration files and data files that are written in XML format.
• Use regular expressions, wildcards, and substring operators to simplify value
matching logic in scripts and pipelines.
• Use the iterative capabilities of the switch construct along with the pipeline or
file processing, and regular expression or wildcard matching capabilities to
reduce the amount of code that is required to process files and other content.
• Use filters and functions to process data. Filters and functions can be used to
make scripting and interactive automation more modular.
Working with Files, the Registry, and Certificate Stores 7-39

• Use the Get-EventLog cmdlet to access the event logs. The Newest parameter
of Get-EventLog can be used instead of relying on Select-Object with the First
parameter. The resultant events can be filtered for matches of specific criteria
by using pipelines with cmdlets such as Where-Object or Group-Object.
• The HKCU and HKLM PSDrives use the Registry PSProvider to allow access to
the Windows registry. Use Get-ItemProperty to access registry values. Other
*-ItemProperty cmdlets can also be used. The Set-Location and Get-ChildItem
cmdlets can be used for navigating the registry hierarchies.
• Use the Export-* and Import-* cmdlets to save and restore objects in persistent
storage. Then use custom code, including cmdlets and constructs such as
switch, foreach, ForEach-Object, and Where-Object to process this data as
necessary. Use CLiXML format for such export and import processing
whenever possible so that the greatest degree of type detail is maintained on
the objects that are imported.
• Use the Compare-Object cmdlet to compare objects. The Sort-Object and
Select-Object cmdlets can be used to assist the comparison. Use foreach or
other iterators to process the results programmatically, or simply let the results
be displayed with the default formatter. Use Sort-Object and Select-Object as
appropriate, along with the Property, SyncWindow, and IncludeEqual
parameters of Compare-Object to compare objects with those that are
imported from persistent storage.

Tools

Tool Use for Where to find it


Set-Location Changing the current location to Windows PowerShell
a specific path within a PSDrive

Get-ChildItem Obtaining a list files and folders at Windows PowerShell


a particular location

Select-String Finding strings that match regular Windows PowerShell


expressions, such as in the
contents of several files

Compare-Object Comparing two sets of objects Windows PowerShell


7-40 Working with Files, the Registry, and Certificate Stores
Managing the Windows Operating System Using Windows PowerShell™ and WMI 8-1

Module 8
Managing the Windows Operating System
Using Windows PowerShell™ and WMI
Contents:
Lesson 1: Introduction to WMI and WMI Objects 8-3
Lesson 2: Managing Disks and Disk Volumes Using Windows PowerShell
with WMI 8-11
Lesson 3: Managing Shadow Copies Using Windows PowerShell with WMI 8-15
Lesson 4: Managing Shared Folders with Windows PowerShell and WMI 8-19
Lesson 5: Managing Terminal Services with WMI 8-22
Lesson 6: Managing IIS 7.0 with WMI 8-29
Lab: Managing the Windows Operating System with Windows PowerShell
and WMI 8-33
8-2 Managing the Windows Operating System Using Windows PowerShell™ and WMI

Module Overview

Windows Management Instrumentation (WMI) is a management technology that


is used to configure, manage, and troubleshoot diverse applications and services in
the Windows platform. WMI can also enable you to carry out key administrative
functions on the server itself, such as remotely defragmenting a disk volume or
creating a share on a remote server.
Key Microsoft applications, such as Microsoft Office Communications Server 2007,
and built-in services, such as Terminal Services, use WMI to a considerable degree.
This module describes WMI and the WMI features that are provided by Windows
PowerShell.

Additional Reading:
For more information about the Distributed Management Task Force, see the
DMTF Web site.
Managing the Windows Operating System Using Windows PowerShell™ and WMI 8-3

MCT USE ONLY. STUDENT USE PROHIBITED


Lesson 1
Introduction to WMI and WMI Objects

You can use Windows PowerShell to access and use WMI to assist in configuring
applications.
This lesson describes WMI functions and how to use the Windows PowerShell
WMI functionality. The lesson also provides a way to find WMI classes that will
help you to manage and administer systems.
8-4 Managing the Windows Operating System Using Windows PowerShell™ and WMI

What Is WMI?

Key Points
WMI is a technology that enables you to obtain management information and
configure settings for applications and services that are running on the Windows
platform.
WMI has been built into Windows since Windows® 2000. As the Microsoft
operating systems and applications have matured, WMI has become a more
fundamental part of the overall management story.
Question: Which applications in your environment are WMI-accessible?

Additional Reading:
• For basic information about WMI, please see Secrets of Windows Management
Instrumentation: Troubleshooting and Tips
• For an overview of WMI, please see Windows Management Instrumentation
• For information on how to use WMI, see WMI and Windows PowerShell:
Mastering PowerShell in your Lunch Break -- Day 5: Using WMI
Managing the Windows Operating System Using Windows PowerShell™ and WMI 8-5

WMI Data Structures

Key Points
In order to use Windows PowerShell and WMI effectively, you need to understand
how WMI information is structured. Key components of WMI are:
• Namespaces: WMI uses the concept of hierarchal namespaces to organize the
information and functions within WMI. Typically, namespaces align to
products such as Windows, Domain Name System (DNS), Internet
Information Services (IIS), etc, but they do not have to.
• Classes: Each node in the WMI namespaces can contain zero, one, or more
WMI classes. Each class represents a manageable component (for example, a
disk or a Web site). Classes can also contain methods that perform useful
functions.
• Instances: A class instance is a real-world occurrence of a class.

In addition to the methods supplied via a specific instance, WMI also implements
the concept of a static method. Static methods are used to perform a task that is
not directly related to a specific instance.
Question: What are the security issues with WMI?
8-6 Managing the Windows Operating System Using Windows PowerShell™ and WMI

Demonstration: Using WMI Explorer

Question: How would you use WMI Explorer to help you use Windows
PowerShell at your workplace?
Managing the Windows Operating System Using Windows PowerShell™ and WMI 8-7

Get-WMIObject Cmdlet and [WMI] Type Accelerator

Key Points
Get-WMIObject is the Windows PowerShell cmdlet that you use to integrate
with WMI.
The syntax for the Get-WMIObject cmdlet (not the List form) is as follows:

Get-WMIObject [-class] <string>


[[-property] <string[]>]
[-namespace <string>]
[-computername <string>[]>]
[-filter <string>]
[-credential <PSCredential>]
[<CommonParameters>]

Or as follows:

Get-WMIObject -query <string>


[-namespace <string>]
[-computername <string>[]>]
[-credential <PSCredential>]
[<CommonParameters>]
8-8 Managing the Windows Operating System Using Windows PowerShell™ and WMI

Windows PowerShell provides several type accelerators for use with WMI. The two
most important of these type accelerators are:
• [WMI]
• [WMICLASS]

The [WMI] accelerator can be used to query an instance of a particular WMI object.
This creates a reference to this object in Windows PowerShell.

Question: Where can you find more information about WMI classes?

Additional Reading:
• For basic information on WMI and CIM, see WMI and CIM Concepts and
Terminology
• For more information about the Distributed Management Task Force, Inc., see
their Web site.
Managing the Windows Operating System Using Windows PowerShell™ and WMI 8-9

Get-WMIObject Cmdlet and [WMICLASS] Type Accelerator

Key Points
The [WMICLASS] accelerator can be used to create an instance of a particular WMI
class. This approach creates a reference object to the specified WMI class in
Windows PowerShell.
An object created with the [WMICLASS] accelerator can then be used to invoke
static methods on the particular WMI class.
For example, the Create method of the Win32_Share WMI class could be used to
create a shared folder.
8-10 Managing the Windows Operating System Using Windows PowerShell™ and WMI

Listing WMI Object Classes with Get-WMIObject -List

Key Points
The Get-WMIObject -List cmdlet provides a list of all accessible WMI classes. This
list can help you find classes that might be of assistance to you.
WMI objects have a number of properties and methods. You can find these by
using the List parameter.
Properties beginning with two underscores (__) are system related and are not
usually very useful for an administrator.
WMI classes also have methods. You can pipe a class to Get-Member to find which
methods and classes are supported by a given class.

Question: How would you create a text file with all WMI class names included for
reference?
Managing the Windows Operating System Using Windows PowerShell™ and WMI 8-11

Lesson 2
Managing Disks and Disk Volumes Using
Windows PowerShell with WMI

Managing disks is an important aspect of systems administration. WMI provides


access to key disk features that administrators need.
8-12 Managing the Windows Operating System Using Windows PowerShell™ and WMI

Enumerating Disks and Volumes

Key Points
WMI has several classes for working with disks, volumes, and disk I/O. Two key
classes include:
• Win32_Volume: Provides a list of volumes (partitions) on the local computer,
plus methods, including defragmentation
• Win32_DiskDrive: Provides information about physical disk drives in your
system

These classes can be used to manage (disk) storage volumes. You can use
Win32_DiskDrive to obtain information about physical disks and use
Win32_Volume to get information about individual volumes (partitions).

Question: How would you find the definition of Win32_DiskDrive?


Managing the Windows Operating System Using Windows PowerShell™ and WMI 8-13

Defragmenting Disk Volumes

Key Points
The Win32_Volume class contains two useful methods:
• DefragAnalysis
• Defrag

These methods enable you to do the following:


• Determine how defragmented your disk is
• Determine whether defragmentation is recommended
• Carry out a defragmentation

Question: How can you create a list of machines and drives to check for the
defragmentation status and then defragment them if recommended by WMI?
8-14 Managing the Windows Operating System Using Windows PowerShell™ and WMI

Mounting and Dismounting Disk Volumes

Key Points
WMI class Win32_Volume has methods for working with mounted volumes:
• Use the Dismount method to dismount the mounted volume. You might do
this before running a compete chkdsk on the volume.
• Use the AddMountPoint method to add a folder in a parent volume under
which to mount a subordinate (child) volume.
• Use the Mount method to mount a child volume under its parent. Use this
method after a dismount.

Question: When would you use the AddMountPoint and the Mount methods?
Managing the Windows Operating System Using Windows PowerShell™ and WMI 8-15

Lesson 3
Managing Shadow Copies Using Windows
PowerShell with WMI

This lesson explains how to use WMI and volume shadow copies. Listing volume
shadow copies enables you to determine how many shadow copies exist and
provides information about them.
8-16 Managing the Windows Operating System Using Windows PowerShell™ and WMI

Volume Shadow Copies

Key Points
Windows Server 2008 and Windows Server 2003 support volume shadow copies.
The Volume Shadow Copy Service (VSS) provides automatic or manual archival of
the changes to an NTFS volume.
Up to 63 shadow copies can be maintained per volume. Only the changes are
stored, not a complete copy of the volume.
The Previous Versions feature for file sharing or local access is based on volume
shadow copy snapshots. This feature allows users or administrators to retrieve
previous versions of modified or deleted files.

Question: Can you think of possible uses of shadow copies?

Additional Reading:
• For more information on WMI management of volume shadow copies, see
Volume Shadow Copy Service Overview.
• For a description of how VSS works, see How Volume Shadow Copy Service
Works.
Managing the Windows Operating System Using Windows PowerShell™ and WMI 8-17

Configuring Volume Shadow Copies

Key Points
Use the static Create method of the Win32_ShadowCopy WMI class to create a
new VSS shadow copy.

Question: How often would you create a VSS copy and why?

Additional Reading:
For more information on WMI and shadow copies, see:
• Win32_ShadowCopy Class
• Create Method of the Win32_ShadowCopy Class
8-18 Managing the Windows Operating System Using Windows PowerShell™ and WMI

Listing Volume Shadow Copies

Key Points
Windows Server 2008 comes with nine classes related to shadow copies. The more
important volume shadow copy WMI classes include:
• Win32_ShadowProvider: Describes the provider that is installed on the
system (useful for troubleshooting)
• Win32_ShadowCopy: Describes each shadow copy that is in use
• Win32_ShadowStorage: Shows shadow copy storage that is in use
• Win32_ShadowContext: Creates shadow copy contexts

The Windows vssadmin.exe command enables command-line management of VSS


and, in effect, duplicates the WMI functionality.
You can use gwmi Win32_ShadowCopy to retrieve a list of shadow copies on the
computer.

Question: Can CD-ROM drives have a shadow copy?


Managing the Windows Operating System Using Windows PowerShell™ and WMI 8-19

Lesson 4
Managing Shared Folders with Windows
PowerShell and WMI

This lesson explains how to manage shared folders using WMI. With WMI you can
list existing shares and create new shared folders.
8-20 Managing the Windows Operating System Using Windows PowerShell™ and WMI

Listing Shared Folders with WMI

Key Points
You can use Get-WMIObject Win32_Share to list the shares on the current
computer.
Instances of the WMI class Win32_Share have a Delete() method, which you can
use to remove a share from the local or remote machine.

Question: When would you use WMI to manage file shares?

Question: Which properties and methods does WMI implement for shared
folders?
Managing the Windows Operating System Using Windows PowerShell™ and WMI 8-21

Creating a Shared Folder with WMI and [WMICLASS]

Key Points
The Win32_share class provides a Create static method. You can use the
[WMICLASS] type accelerator to give you access to the method.

Question: Can you use this class across a network (that is, remotely)?
8-22 Managing the Windows Operating System Using Windows PowerShell™ and WMI

Lesson 5
Managing Terminal Services with WMI

This lesson discusses how to get information from the Terminal Services WMI
provider and where to find out more about Terminal Services and Terminal
Services WMI classes. Administrators will also see how to update settings on
Terminal Servers using WMI.
Managing the Windows Operating System Using Windows PowerShell™ and WMI 8-23

Terminal Services in Windows Server 2008

Key Points
Terminal Services is a key component of Windows Server 2008. It provides a
wealth of new features.
Another key feature is an updated WMI provider that you can use from within
Windows PowerShell.

Question: Do you use Terminal Services currently?

Additional Reading:
For more information on Terminal Services features, see What's New in Terminal
Services for Windows Server 2008
8-24 Managing the Windows Operating System Using Windows PowerShell™ and WMI

Terminal Services WMI Provider

Key Points
The Terminal Services WMI provider has been improved and contains a wealth of
new classes. You can access these WMI classes to manage your terminal server
farm.

Question: How do you manage your terminal server farm currently?

Question: Do you see any advantage of using the new Terminal Services WMI
provider?
Managing the Windows Operating System Using Windows PowerShell™ and WMI 8-25

Getting Terminal Services WMI Classes

Key Points
You can use the Get-WMIObject cmdlet to get a list of WMI classes (use the List
parameter).

Question: Are all these WMI classes useful to an administrator?


8-26 Managing the Windows Operating System Using Windows PowerShell™ and WMI

Retrieving Terminal Services Information from WMI

Key Points:
There are over 40 classes, divided into 5 main sets. Each set is described separately
in MSDN.
Remember that when you retrieve Terminal Services WMI classes, you must
specify the namespace.
Question: How would you find out the individual properties and methods on
each class?

Additional Reading:
For more information about Terminal Services, see Terminal Services WMI
Provider Reference.
Managing the Windows Operating System Using Windows PowerShell™ and WMI 8-27

Configuring Terminal Services with Windows PowerShell


and WMI

Key Points:
Many classes related to Terminal Services contain methods that you can call to
update settings. Some classes also have useful properties. However, not all of the
properties can be set.
Unlike some other classes, setting a new value for the property of an object
instance related to Terminal Services does not actually make the change. To
actually set the value, first assign the value to the instance, then call the Put()
method on the instance that you have just updated.

Question: How would you find out which properties you can set values on?

Question: How would you find out which WMI classes have Windows PowerShell
samples to illustrate their use?
8-28 Managing the Windows Operating System Using Windows PowerShell™ and WMI

Additional Reading:
• For information on WMI classes, see the MSDN Library.
• For information on the Terminal Services WMI provider and related classes,
see Terminal Services WMI Provider Reference.
Managing the Windows Operating System Using Windows PowerShell™ and WMI 8-29

Lesson 6
Managing IIS 7.0 with WMI

This lesson presents examples of managing IIS7 using WMI, including use of the
WMI WebAdministration namespace. Other interfaces such as the .NET
Web.Administration interface are not addressed directly in this lesson. Each of
these interfaces is well-suited to particular styles of management. The ability to
automate Web server administration can help administrators in many scenarios.
8-30 Managing the Windows Operating System Using Windows PowerShell™ and WMI

Administering IIS 7.0 with WMI

Key Points
IIS 7.0 includes some WMI managed objects. These objects are defined in
$env:SystemRoot\System32\inetsrv\w3core.mof and w3isapi.mof.
These WMI classes for IIS 7.0 are different than the IIS 6.0 WMI classes.
You can use WMI providers to manage application pools and Web sites.

Question: What is one advantage of using WMI to manage IIS versus relying solely
on using the XML configuration files?

Additional Reading:
For more information on WMI provider class methods in IIS, see Mapping IIS 6.0
WMI Methods to IIS 7.0 WMI Methods.
Managing the Windows Operating System Using Windows PowerShell™ and WMI 8-31

WMI Namespaces for IIS Management

Key Points:
IIS 7.0 comes with four managed object framework files. Three of these are loaded
into the Root\WMI namespace. The fourth, WebAdministration.mof, is loaded
into the Root\WebManagement namespace.
The classes in these frameworks can be used to manage many aspects of IIS 7.0.
The Root\WebManagement namespace is the most recommended for WMI
management of IIS 7.0.

Question: In which WMI namespaces can the IIS management classes be found?
8-32 Managing the Windows Operating System Using Windows PowerShell™ and WMI

Demonstration: Site Management Using WMI

Question: How would you use WMI for managing your site?

Additional Reading:
For more information on site management, see:
• IIS 7.0: IIS WMI Provider Reference
• Managing Sites with IIS 7.0's WMI Provider
Managing the Windows Operating System Using Windows PowerShell™ and WMI 8-33

Lab: Managing the Windows Operating System


with Windows PowerShell and WMI

Exercise 1: Using WMI Classes in Windows PowerShell


Scenario
As an administrator for Woodgrove Bank, you often need to retrieve information
about computers on your network. This information includes inventory
information, such as operating system version numbers, and operational
information, such as the processes that are currently running on a computer. You
have chosen to use Windows Management Instrumentation (WMI) classes in
Windows PowerShell to retrieve and process this information.
8-34 Managing the Windows Operating System Using Windows PowerShell™ and WMI

Exercise Overview
In this exercise, you will use WMI classes in Windows PowerShell.
The main tasks for this exercise are as follows:
1. Start the 6434A-NYC-DC1 virtual computer and log on as Administrator.
2. Retrieve the operating system and service pack version information from a
computer.
3. Retrieve information related to services that are installed on a computer.
4. Remove a shared folder from a computer.

f Task 1: Start the 6434A-NYC-DC1 virtual computer and log on as


Administrator
• Start the 6434A-NYC-DC1 virtual computer and log on as Administrator
using the password Pa$$w0rd.
• Open Windows PowerShell.

f Task 2: Retrieve the operating system and service pack version


information from a computer
• Retrieve all instances of the Win32_OperatingSystem WMI class from the
local computer.
• Display only those properties that contain the operating system build number
and the major version number of the latest installed service pack.
• Complete this task using a technique that can be used either for the local
computer or for remote computers.

f Task 3: Retrieve information related to services that are installed on a


computer
• Create a list of installed services that includes the service name, the user
account that the service uses to log on, and the start mode that the service is
configured to use.
Managing the Windows Operating System Using Windows PowerShell™ and WMI 8-35

f Task 4: Remove a shared folder from a computer


• Retrieve all instances of the Win32_Share class that have a Name property
containing "FileShare".
• Execute the Delete() method of all retrieved Win32_Share instances.

Results: After this exercise, you should have retrieved inventory and operational
information from a computer using a technique that can be used for either the local
computer or for remote computers.

Exercise 2: Using WMI Type Accelerators


Scenario
You administer file servers for Woodgrove Bank. Creation of new shared folders
and running programs remotely are common tasks in your job. As new committees
and projects form every week, you need to ensure that people have access to
shared folders to support their latest endeavors. As a part of your remote
management duties, you frequently need to launch software on servers and
workstations throughout the organization. You need to create a new shared folder
so that users can access shared documents on one of the file servers that you
maintain at Woodgrove Bank. You also need to use Windows PowerShell to launch
new processes, including doing so on remote computers. You choose to use WMI
type accelerators to accomplish these tasks.

Exercise Overview
In this exercise, you will create a shared folder and launch a new process.
The main tasks for this exercise are as follows:
1. Create a folder to share.
2. Share the folder.
3. Launch a new process.

f Task 1: Create a folder to share


• Create a folder named C:\SharedDocuments.
8-36 Managing the Windows Operating System Using Windows PowerShell™ and WMI

f Task 2: Share the folder


• Use the [WMICLASS] type accelerator to retrieve the Win32_Share class.
• Use the Create() method of the Win32_Share class to create a new shared
folder named Docs for the C:\SharedDocuments folder.

f Task 3: Launch a new process


• Use the [WMICLASS] type accelerator to retrieve the Win32_Process class.
• Use the Create() method of the Win32_Process class to launch Windows
Notepad.

Results: After this exercise, you should have created a new shared folder and launched
Windows Notepad.

Exercise 3: Managing Disk Volumes in Windows PowerShell


Scenario
In this exercise, you will produce an inventory report of the disk volumes on a
computer. Your report will include information such as total size, space available,
and other information, and will be used for capacity planning on the current and
future servers that you administer at Woodgrove Bank. You also need to produce
reports that list all the volumes that are attached to a computer, for inventory
purposes.

Exercise Overview
In this exercise, you will manage disk volumes in Windows PowerShell.
The main tasks for this exercise are as follows:
1. Report on free disk space for local disk volumes.
2. Report on all volumes attached to a computer.

f Task 1: Report on free disk space for local disk volumes


• Create a report that uses the Win32_Volume class to display the drive letter,
total space, and free space for local hard disks only.
• Display the report in table format on the screen.
Managing the Windows Operating System Using Windows PowerShell™ and WMI 8-37

f Task 2: Report on all volumes attached to a computer


• Create a report that shows all attached volumes. The report should include the
volume name (drive letter) and its drive type number.
• Save the report in a CSV file named DriveInventory.csv.

Results: After this exercise, you should have produced drive volume reports that can
be used for inventory and capacity planning purposes.

Exercise 4: Defragmenting Disk Volumes Using Windows


PowerShell
Scenario
Many of the NTFS volumes that you administer at Woodgrove Bank are heavily
utilized, with files being created, modified, and deleted at a rapid rate. As such, the
allocation of clusters to the files on these volumes can quickly become fragmented.
Your manager has asked if you can automate scheduling of defragmentation of
these values based on a needed versus not needed analysis and to track the
frequency and dates of when each volume is defragmented. As the first step in
prototyping this automation, you will use WMI in Windows PowerShell to
defragment a small hard disk.

Exercise Overview
The main tasks for this exercise are as follows:
1. Defragment the E drive.

f Task 1: Defragment the E drive


• Use WMI to obtain the Win32_Volume instance that represents the E drive.
• Note that the backslash (\) character is a special character in WMI. If you
specify a filter, you must type two backslashes. For example, instead of "E:\,"
you would type "E:\\."
• Run the Defrag() method of the instance that you obtained.
8-38 Managing the Windows Operating System Using Windows PowerShell™ and WMI

Results: After this exercise, you should have defragmented the E drive on your virtual
machine.

Exercise 5: Managing IIS 7.0 Properties Using WMI


Scenario
You are a Web server administrator for Woodgrove Bank. You need to write a set
of Windows PowerShell functions that will make it easier and faster to maintain
Web sites running under IIS 7.0.

Exercise Overview
In this exercise, students will manage IIS 7.0 properties by using WMI.
The main tasks for this exercise are as follows:
1. Start the 6434A-NYC-DC1 virtual machine and log on as Administrator.
2. Install IIS 7.0
3. Write the Get-WebSiteStatus function.
4. Write the Restart-WebSite function.

f Task 1: Start the 6434A-NYC-DC1 virtual machine and log on as


Administrator
• Start the 6434A-NYC-DC1 virtual machine and log on as Administrator.
• Open Windows PowerShell.

f Task 2: Install IIS 7.0


• Use Server Manager to install IIS 7.0.
• Ensure that you select the following Management Tools:
• IIS Management Console
• IIS Management Scripts and Tools
• Management Service
• IIS 6 Management Compatibility
Managing the Windows Operating System Using Windows PowerShell™ and WMI 8-39

f Task 3: Write the Get-WebSiteStatus function


• Write a Windows PowerShell function named Get-WebSiteStatus.
The function must accept the name of a Web site as an input argument, and
the function must output the state of the Web site: Running, Stopped,
Stopping, Starting, or Unknown.
The function should use WMI to retrieve the specified Web site, execute its
GetState() method, and display the result.
• Use the function to retrieve the status of the default Web site.

f Task 4: Write the Restart-WebSite function


• Write a Windows PowerShell function named Restart-WebSite.
The function must accept the name of a Web site as an input argument.
The function should retrieve that Web site and execute its Stop() and
Start() methods.
• Use the function to restart the default Web site.

Results: After this exercise, you should have written two functions that help make
IIS 7.0 Web site maintenance easier.
8-40 Managing the Windows Operating System Using Windows PowerShell™ and WMI

Lab Review
Managing the Windows Operating System Using Windows PowerShell™ and WMI 8-41

Module Review and Takeaways

Review Questions
1. Where can you find more information about WMI?
2. Where are WMI classes, WMI class properties, and WMI class methods
documented?
3. Where can you get WMI sample code relating to WMI and Windows
PowerShell?
4. Identify an alternative technology besides the Iis.msc console that is available
in Windows PowerShell for managing IIS 7.0.
8-42 Managing the Windows Operating System Using Windows PowerShell™ and WMI

Common Issues related to WMI and Windows PowerShell


Identify the causes for the following common issues related to WMI and Windows
PowerShell and fill in the troubleshooting tips. For answers, refer to relevant
lessons in the module.

Issue Troubleshooting tip


Not all WMI classes work with all
operating systems.

There are thousands of classes. How


do you find the ones that you need?

You cannot get a particular class to


do what you want.

The documentation on WMI is


scanty.

Access to many of the details of a


Web site yields null results when you
use the WMI
Root/WebAdministration
namespace.

Real-world Issues and Scenarios


1. The Sales and Products databases in a pharmaceutical company are on
different servers, each of which also hosts other databases. How could you
manage these systems using WMI?
2. The Marketing department of an electronics distributor hosts several Web sites
for the use of current and potential customers. Which technologies would you
use to manage these servers from a central location?

Best Practices related to WMI and Windows PowerShell


Supplement or modify the following best practices for your own work situations:
• Use WMI Explorer to discover more details about WMI.
• Consider writing some simple wrapper functions to speed up your use of WMI
classes.
Managing the Windows Operating System Using Windows PowerShell™ and WMI 8-43

• Create richer functions to perform common administrative features and add


them to your $profile file.
• Learn both the WMI and .NET management approaches for IIS 7.0
administration.
• Use the WMI management approach for IIS 7.0 when you need to quickly
modify specific sections or elements.

Tools

Tool Use for Where to find it


WMI Explorer Searching WMI Using your favorite search
engine, search for it on the
Internet

MSDN WMI wiki Locating information WMI Classes on MSDN


on WMI classes that Windows PowerShell
you can access with samples under Community
Windows PowerShell Content

Appcmd.exe Text-oriented Windows Server 2008 IIS 7.0


management of IIS 7.0

WMI Managed object access Windows PowerShell


Root\WebAdministration to IIS 7.0 configuration
namespace and management
8-44 Managing the Windows Operating System Using Windows PowerShell™ and WMI
Administering Microsoft® Active Directory® with Windows PowerShell™ 9-1

Module 9
Administering Microsoft® Active Directory®
with Windows PowerShell™
Contents:
Lesson 1: Administering Domains and Forests Using .NET Objects 9-3
Lesson 2: Managing User Accounts and Groups Using ADSI 9-9
Lesson 3: Managing Relationships Between Users and Groups 9-17
Lesson 4: Web Administration Using IIS 7.0 9-23
Lab: Administering Active Directory with Windows PowerShell 9-27
9-2 Administering Microsoft® Active Directory® with Windows PowerShell™

Module Overview

The needs of many organizations greatly warrant the use of automation to meet
some of the required administration of users, contacts, groups, organizational units
(OUs), and other objects in Active Directory directory services.
You can use several separate sets of objects to administer Active Directory using
Windows PowerShell. These objects include the .NET Active Directory classes, the
shell.application COM object and the [ADSI] type accelerator. You can also use
third-party tools to administer Active Directory.
This module explains how to write scripts that use these different methods in
order to perform Active Directory administration tasks. Operations include
changing the domain and forest functional level, moving Flexible Single Master
Operation (FSMO) roles, and creating and modifying objects such as groups and
user accounts. Managing relationships between user accounts and groups is also
demonstrated.
Administering Microsoft® Active Directory® with Windows PowerShell™ 9-3

Lesson 1
Administering Domains and Forests Using
.NET Objects

The .NET Framework has two classes that you can use to work with
Active Directory.
This lesson introduces you to using these two classes to automate certain tasks in
forest-wide and domain-wide management with Windows PowerShell.
9-4 Administering Microsoft® Active Directory® with Windows PowerShell™

System.DirectoryServices.ActiveDirectory.Domain Class

Key Points
.NET Framework includes a class for working with certain aspects of an
Active Directory domain. The class is called
System.DirectoryServices.ActiveDirectory.Domain. You can invoke the
GetCurrentDomain method on that class to return a reference object for the
current domain. Properties on this object include a forest object, and any child
domains of this domain.
Several other methods are available to perform administrative tasks at the domain
level. These methods include VerifyTrustRelationship and
RepairTrustRelationship.

Question: What are the benefits of using Windows PowerShell cmdlets to manage
Active Directory classes?
Administering Microsoft® Active Directory® with Windows PowerShell™ 9-5

System.DirectoryServices.ActiveDirectory.Forest Class

Key Points:
.NET Framework includes a class for working with certain aspects of an
Active Directory forest. The class is called
System.DirectoryServices.ActiveDirectory.Forest. You can invoke the
GetCurrentForest method on that class to return a reference object for the current
forest. Several additional methods are available to perform administrative tasks at
the forest level.
Forest operations include creating and deleting trust relationships, finding global
catalogs (GCs), getting all existing trust relationships, and managing security
identifier (SID) filtering.

Question: Which operations can be performed with a reference to the current


Active Directory forest?
9-6 Administering Microsoft® Active Directory® with Windows PowerShell™

Transferring FSMO Roles

Key Points
FSMO roles can be transferred using methods on a domain or forest. You first need
to get a reference to the domain controller to which you wish to move the FSMO
role. You can also seize a FSMO role using the $dom object. You might use these
commands to move FSMO roles as part of routine maintenance or seize a role in
case the existing role holder fails or is offline.
This approach can be used with any of the three domain FSMO roles:
• Relative identifier (RID) master
• Primary domain controller (PDC) emulator
• Infrastructure master

This approach can also be used for either of the two forest FSMO roles: schema
master and domain naming master.
Question: Which transfer method would work better for you? Why?
Administering Microsoft® Active Directory® with Windows PowerShell™ 9-7

Finding, Activating, and Decommissioning Global


Catalog Servers

Key Points:
Use the FindGlobalCatalog() method on the forest object to list all global catalog
servers in the forest.
Use the DisableGlobalCatalog to disable the gc function. Use the $dom object to
find a domain controller; then use the EnableGlobalCatalog method on the
domain controller to enable the global catalog service on that domain controller.

Use Get-Member to find other similar methods that are available.

Note: Ensure that a sufficient number of global catalog servers are deployed throughout
a forest. WMI does allow you to remove all global catalogs in your forest.

Question: How would you query for all current global catalog servers in an
Active Directory forest?
9-8 Administering Microsoft® Active Directory® with Windows PowerShell™

Raising Domain Functionality and Forest Functionality

Key Points
Use the RaiseDomainFunctionality method on the domain reference object to
adjust the domain functional level (DFL) for a specific domain.
Use the RaiseForestFunctionality method on the forest object to adjust the forest
functional level (FFL) for the forest.

Question: Do your Active Directory forests still have Windows® 2000 Server or
Windows Server® 2003 domain controllers?

Question: How would you automate the discovery of the operating system used by
each domain controller and the DFL of each domain in a forest?
Administering Microsoft® Active Directory® with Windows PowerShell™ 9-9

Lesson 2
Managing User Accounts and Groups Using
ADSI

The Lightweight Directory Access Protocol (LDAP) is the most prominent protocol
used across the network. Many tools, utilities, and application programming
interfaces (APIs) use LDAP directly. However, the majority of Windows-based
software for accessing the directory uses the ADSI. ADSI is an API that is based on
Component Object Model (COM). It hides many of the details of using LDAP and
some other protocols.
This lesson focuses on how to use ADSI to query and search, create, modify, and
delete objects in Active Directory. Such skills enable administrators to customize
and automate the configuration and management of Active Directory
environments.
9-10 Administering Microsoft® Active Directory® with Windows PowerShell™

Active Directory Services Interface

Key Points
The ADSI is a set of COM interfaces that can be used to access Active Directory. It
can also access Windows NT® Security Account Manager (SAM) style domains
(local per workstation or server) and other non-Microsoft directories.
Availability of ADSI in Windows PowerShell facilitates the querying, searching,
creation, deletion, and modification of objects in Active Directory.

Question: How would you create a reference to an existing object in your


Active Directory?

Additional Reading:
• For more information on the LDAP URL Format, see RFC 2255.
• For more information on using the [ADSI] accelerator, see Mastering
PowerShell in your Lunch Break: Day 7: Manage Users
Administering Microsoft® Active Directory® with Windows PowerShell™ 9-11

Demonstration: Using an LDAP URL for a Domain, OU, or


Other Object

Question: How would you write an LDAP URL to refer to an OU in your own
Active Directory environment?
9-12 Administering Microsoft® Active Directory® with Windows PowerShell™

Demonstration: Creating OUs

Question: What are the essential steps for creating an OU?

Question: How would you write a script that prompts for a parent OU name and a
new child OU name and performs the creation steps with that information?
Administering Microsoft® Active Directory® with Windows PowerShell™ 9-13

Creating User Accounts

Key Points
User accounts are created in the same way as OUs. The object class is user and the
RDN includes a common name (CN=) tag rather than the OU= tag used by OUs.
You can set many more attributes by using the Put() method before invoking the
SetInfo() method.
Look up the Active Directory schema for the available object classes and attribute
types. The attribute types that are listed as mandatory or optional on the user class
can be used on user accounts. Consider class inheritance, such as the
organizationalPerson, and person lineage of the user object class. Furthermore,
auxiliary classes also include additional sets of attributes in such a class hierarchy.
User accounts can be created using the ADSI Create method, similar to how
organizational units are created.

Question: How would you write a simple function to add a user account to
Active Directory, accepting basic arguments such as the name and/or OU?
9-14 Administering Microsoft® Active Directory® with Windows PowerShell™

Additional Reading:
• For an overview of the Active Directory schema, see Active Directory Schema
on the MSDN.
Administering Microsoft® Active Directory® with Windows PowerShell™ 9-15

Creating Groups

Key Points
You can create and manage various types of groups in Windows PowerShell using
ADSI. The two types of groups supported in Active Directory are:
• Security groups
• Distribution groups
The three configurable scopes of groups in Active Directory are:
• Global
• Domain local
• Universal

Question: How would you create a global security group using ADSI in
Windows PowerShell?

Additional Reading:
For an example of creating a group with ADSI in Windows PowerShell, see Arul
Kumaravel's WebLog.
9-16 Administering Microsoft® Active Directory® with Windows PowerShell™

Demonstration: Modifying Existing User Account Properties

Question: How would you modify the same property of several users at once?
Administering Microsoft® Active Directory® with Windows PowerShell™ 9-17

Lesson 3
Managing Relationships Between Users
and Groups

The Active Directory schema is extensible. Nearly any type of information can be
used in the directory of an organization. Users of Active Directory can benefit from
up-to-date information being maintained in the directory.
This lesson presents some techniques for managing organizational information
and group nesting management capabilities that can facilitate many administrative
tasks.
9-18 Administering Microsoft® Active Directory® with Windows PowerShell™

Setting Organizational Information: Job Title,


Department, Company

Key Points
Nearly any attribute of an Active Directory object can be modified using ADSI, if
permissions allow.
Additional attributes can be added to the schema of an AD DS forest or AD LDS
instance. To modify an attribute, you must obtain a reference to the object, then
use the Put method to add or modify the attribute. Then you must commit this to
the directory using the SetInfo method.

Question: How would you write a Windows PowerShell function to modify the
organizational information for one or more users?
Administering Microsoft® Active Directory® with Windows PowerShell™ 9-19

Assigning Manager Relationships

Key Points
The manager attribute on organizational person objects (contacts, Internet
organizational person, and user accounts) is handled specially. Modifying it
changes the manager attribute of the object that is being modified and the
directReports attribute of the manager.object.

Question: How would you write a Windows PowerShell function that would
modify the manager attribute for a user?

Question: How would you write a function that would move a user (or users) to
another OU, change group memberships, and manager attributes together?
9-20 Administering Microsoft® Active Directory® with Windows PowerShell™

Demonstration: Traversing Management Hierarchy

Question: How would you write a Windows PowerShell function to return all of
the people who work for a particular manager?
Administering Microsoft® Active Directory® with Windows PowerShell™ 9-21

Modifying Group Membership

Key Points
You can obtain a reference to an existing group by using the [ADSI] accelerator, or
by doing a search.
The Add and Remove methods can be used to change the group membership.
Alternatively, you can use the PutEx method.
After changing the membership, you must commit it to the directory using the
SetInfo method.

Question: Given the DN of a group and the DN of a user, how would you add the
user as a member of the group?
9-22 Administering Microsoft® Active Directory® with Windows PowerShell™

Demonstration: Querying a Nested Group Hierarchy

Question: How would you enumerate all the groups that a user is a member of?
Administering Microsoft® Active Directory® with Windows PowerShell™ 9-23

Lesson 4
Web Administration Using IIS 7.0

Internet Information Services 7.0 (IIS 7.0) can be managed using many interfaces,
including WMI. This lesson focuses on using the .NET Web.Administration
interface of IIS 7.0 to facilitate IIS management. Although the WMI management
interfaces for IIS 7.0 management are functional and useful for quick operations,
the .NET Web.Administration interface is preferred for serious IIS management
work. IIS administrators should learn both approaches, the WMI and .NET ways,
in addition to becoming familiar with using appcmd.exe and XML configuration
file and metabase edits, and choose the best tools for any particular management
task.
9-24 Administering Microsoft® Active Directory® with Windows PowerShell™

IIS 7.0 .NET Interface Web.Administration

Key Points
The .NET Microsoft.Web.Administration assembly includes classes that you can
use to monitor and manage IIS 7.0.
The ServerManager class provides the principal interface and allows access to
several subcomponents that are represented by other classes.

Question: Are there any advantages to using the .NET class for
Web.Administration instead of directly using the WMI interface?

Additional Reading:
For more information about managing IIS with classes, see CarlosAg Blog:
Microsoft.Web.Administration in IIS 7.
Administering Microsoft® Active Directory® with Windows PowerShell™ 9-25

Web Server Management Using Web.Administration

Key Points
The .NET Microsoft.Web.Administration assembly includes classes that can be
used to monitor and manage IIS 7.0.
The Microsoft.Web.Administration.ServerManager class provides .NET access to
application pools, sites, and worker processes. You can use the Sites property to
manage existing sites and create new sites.
The .NET management interface for managing IIS is used for a full installation of
Windows Server 2008.
The WMI classes are used to manage either Server Core or Full Installation servers.

Question: What is the advantage of using the .NET Web.Administration interface


as opposed to using the WMI WebAdministration namespace?

Additional Reading:
For more information on Web server management, see .NET Framework Class
Library: ServerManager Class.
9-26 Administering Microsoft® Active Directory® with Windows PowerShell™

Demonstration: Web Site Creation

Question: Are changes that you make to a Web.Administration.ServerManager


object, such as via the Sites.Add method, permanent by default?

Question: If not, which method is used to make these changes permanent?


Administering Microsoft® Active Directory® with Windows PowerShell™ 9-27

Lab: Administering Active Directory with


Windows PowerShell

Exercise 1: Managing Active Directory Domain and Forest


Properties
Scenario
You are an administrator for Woodgrove Bank who is responsible for systems
security. You and your IT director are concerned about maintaining adequate
password policies, because many bank computers, such as those used for teller
access, are near public view. You have heard reports of security breaches at other
banks due to weak password security. You need to create a report that displays the
password policies for your Active Directory domain.
9-28 Administering Microsoft® Active Directory® with Windows PowerShell™

Exercise Overview
In this exercise, students will manage Active Directory domain and forest
properties.
The main tasks for this exercise are as follows:
1. Obtain a reference to the domain.
2. Display domain password policy properties.

f Task 1: Start the 6434A-NYC-DC1 virtual machine and log on as


Administrator
• Start the 6434A-NYC-DC1 virtual machine and log on as Administrator using
the password Pa$$w0rd.

f Task 2: Obtain a reference to the domain


• Use Windows PowerShell to obtain a reference to the current domain.
• Store the reference in the variable $domain.

f Task 3: Display domain password policy properties


• Display the list of domain properties by using Get-Member.
• Display the following settings from the password policy for the domain:
• Minimum password length
• Password history length
• Maximum password age

Results: After this exercise, you should have displayed the domain password policies
for your domain.
Administering Microsoft® Active Directory® with Windows PowerShell™ 9-29

Exercise 2: Maintaining Active Directory with ADSI


Scenario
You are a directory administrator for Woodgrove Bank. Each week, the company
provides you with a text file that lists new employees and the branches that they
work in. The file is in comma-separated values (CSV) format. You need to use the
file to create new Active Directory user accounts. You have chosen to use the CSV
import capabilities and the ADSI type accelerator in Windows PowerShell to
accomplish this.

Exercise Overview
In this exercise, students will maintain Active Directory objects using ADSI in
Windows PowerShell.
The main tasks for this exercise are as follows:
1. Write a script that creates an organizational unit.
2. Create a sample CSV file.
3. Write a script that imports the CSV file and creates user accounts.

f Task 1: Write a script that creates an organizational unit


• Use Windows Notepad to create an OU.
• In the file, type the following information:
• $dom = [ADSI]"LDAP://dc=woodgrovebank,dc=com"
• $ou = $dom.Create( "organizationalUnit", "ou=Tellers" )
• $ou.SetInfo()
• Save the file.
9-30 Administering Microsoft® Active Directory® with Windows PowerShell™

f Task 2: Create a sample CSV file


• Use Notepad to create a file named Users.csv.
• Double-check to be sure that Windows Notepad does not add a "txt" filename
extension.
• In the file, type the following information:
• FullName,LogonName,Branch
• Jesper Aaberg,Jesper,New York City
• Syed Abbas,Syed,Seattle
• Save the file.

f Task 3: Write a script that imports the CSV file and creates
user accounts
• Write a Windows PowerShell script that performs the following steps:
• Read the contents of the CSV file.
• For each line in the file, excluding the first row, create a new user account.
• The "FullName" column is the canonical name (CN) of the user.
• The "LogonName" column is the SAM Account Name of the user.
• The "Branch" column is the Department of the user.
• The new user accounts should be disabled (this is the default).
• The user accounts must be created in the Tellers OU.

Results: After this exercise, you should have written a script that reads a CSV file and
uses the information in it to create new user accounts.
Administering Microsoft® Active Directory® with Windows PowerShell™ 9-31

Exercise 3: Maintaining Relationships in Active Directory


with ADSI
Scenario
At Woodgrove Bank, corporate reorganizations seem to be a fairly regular exercise.
Even without such reorganizations, the turnover rate for some of the bank jobs
seems to be going for a world record, and promotions in the branch offices seem to
occur every month. As a directory administrator supporting the Human Resources
department, you need to maintain up-to-date manager and direct report
information for the enterprise. Each time that a new person is promoted or hired to
a manager position, people who report directly to that person need to be updated
in the directory. As an Active Directory administrator, you are responsible for
maintaining reporting hierarchy information for the organization. You regularly
update the manager attribute for several users in the Woodgrove Bank Active
Directory domain. You decide to start by configuring the user accounts for workers
in the Seattle branch with the appropriate manager.

Exercise Overview
In this exercise, students will manage relationships between user accounts and
groups using ADSI in Windows PowerShell.
The main tasks for this exercise are as follows:
1. Retrieve the user account of the new manager.
2. Update the accounts of selected users.

f Task 1: Retrieve the user account of the new manager


• Run a command that retrieves the user account for Kristian Gotsch in the
Executives OU. Store the account in the variable $mgr.
• Set the variable $mgrname to contain the DN of Kristian Gotsch.
9-32 Administering Microsoft® Active Directory® with Windows PowerShell™

f Task 2: Update the accounts of selected users


• Dot source the GetUser.ps1 and SetUser.ps1 scripts into the shell.
• Write a one-liner that performs the following steps:
• Retrieves all user accounts in the domain
• Keeps only those user accounts whose Department attribute is "Seattle."
• Update the manager attribute of those accounts to have Kristian Gotsch
as the manager.

Results: After this exercise, you should have updated two user accounts to have a new
manager attribute.

Exercise 4: Managing IIS 7.0 with the .NET


Web.Administration.ServerManager Class

Scenario
You are a Web server administrator for Woodgrove Bank. For security reasons,
new promotions and new products need to be published to separate Web sites that
are distinct from the regular Web sites for the bank. Because these new promotions
come out regularly, new Web sites need to be created frequently. You want to write
a Windows PowerShell script that automates the creation of new IIS 7.0 Web sites.

Exercise Overview
In this exercise, students will manage IIS 7.0 by using the .NET
Web.Administration.ServerManager class.
The main tasks for this exercise are as follows:
1. Write a Windows PowerShell script that creates a new Web site.

f Task 1: Write a Windows PowerShell script that creates a new Web site
• Write a script that accepts several parameters:
• Web site root directory path
• Web site name
• Web site HTTP port
Administering Microsoft® Active Directory® with Windows PowerShell™ 9-33

The script should create a new IIS 7.0 Web site on the local computer, using
the parameters that are provided.
• Test the script by using it to create a new Web site named MyWeb, with a root
path of C:\Inetpub\wwwroot2, and a port of 8080.
• Check your results in Microsoft® Internet Explorer® by browsing to
http://localhost:8080.

Results: After this exercise, you should have created a script that automates the
creation of new IIS 7.0 Web sites.
9-34 Administering Microsoft® Active Directory® with Windows PowerShell™

Lab Review
Administering Microsoft® Active Directory® with Windows PowerShell™ 9-35

Module Review and Takeaways

Review Questions
1. Which technique is used for finding all global catalog servers in a forest?
2. How can properties of a user account be displayed in Windows PowerShell?
3. How would you expand the nested group membership of a user?

Common Issues related to Administering Active Directory


Identify the causes for the following common issues related to administering Active
Directory and fill in the troubleshooting tips. For answers, refer to relevant lessons
in the module.

Issue Troubleshooting tip

An exception is thrown when you use


the [ADSI] accelerator.

When you access an attribute of an


Active Directory object as a property
of a Windows PowerShell object, a
type name is returned instead of the
actual attribute value.
9-36 Administering Microsoft® Active Directory® with Windows PowerShell™

Issue Troubleshooting tip

The changes to IIS 7.0 Web server


configuration, such as adding a site,
are lost when you use the
Web.Administration.ServerManage
r class.

Real-world Issues and Scenarios


The Human Resources department needs to quickly run queries of the reporting
hierarchy against Active Directory. For example, they might need to determine
everyone who works for a certain director, including the managers who report
directly to the director and all subordinates who work for those managers as well.
Another common request is when the name of an employee is known, and the
chain of command up the management hierarchy from this person is needed. How
can you accommodate both these kinds of requests using Windows PowerShell
and ADSI?

Best Practices related to Administering Active Directory


Supplement or modify the following best practices for your own work situations:
• Define Active Directory access functions to meet your common needs for
Active Directory management.
• Define a disaster recovery plan for FSMO role placement on domain
controllers, and investigate the benefits of automating role transfers.
• Use pipelines with Active Directory access functions instead of making each
function handle all aspects of a problem.
• Learn both the WMI and .NET management approaches for administering IIS
7.0.
• Use the .NET Web.Administration interface for IIS 7.0 management whenever
possible.
Administering Microsoft® Active Directory® with Windows PowerShell™ 9-37

Tools

Tool Use for Where to find it


[ADSI] Referring to objects in Active Windows
Directory by name PowerShell

DirectorySearcher class Finding objects using LDAP Windows


queries PowerShell

.NET Structured management of Windows


Microsoft.Web.Administratio IIS 7.0 PowerShell
n assembly
Administering Group Policy in Windows PowerShell™ Using COM 10-1

Module 10
Administering Group Policy in Windows
PowerShell™ Using COM
Contents:
Lesson 1: Managing GPOs Using the GPMC COM Interface 10-3
Lesson 2: Managing Group Policy Objects 10-11
Lesson 3: Reporting Group Policy 10-15
Lab: Administering Group Policy in Windows PowerShell 10-18
10-2 Administering Group Policy in Windows PowerShell™

Module Overview

This module explains how to write scripts to manage Group Policy using the
Group Policy Management Console Component Object Model (GPMC COM)
interface.
As an administrator, you might have to perform the tasks of creating Group Policy
Objects (GPOs), discovering modified GPOs, copying settings from one GPO to
another, and backing up and restoring GPOs.
This module also discusses GPO reporting via Windows PowerShell and the
GPMC COM interface.
Administering Group Policy in Windows PowerShell™ Using COM 10-3

Lesson 1
Managing GPOs Using the GPMC COM
Interface

This lesson introduces the basics of the GPMC COM interoperability and the
GPMC COM interface. This information will help you to develop scripts to manage
and control GPO objects in an efficient and productive manner.
10-4 Administering Group Policy in Windows PowerShell™

Introduction to COM in Windows PowerShell

Key Points

You can use Windows PowerShell to refer to COM objects:


• COM objects are generated by some types and methods.
• COM objects can be generated using the New-Object cmdlet with the
ComObject parameter.
• Methods and properties of COM objects are accessed as if they were .NET
objects in Windows PowerShell.

To make a reference to a COM object, use the New-Object cmdlet and include the
ComObject parameter in addition to the COM class name.

Question: How would you create a reference object to automate management of


Internet Explorer via COM?
Administering Group Policy in Windows PowerShell™ Using COM 10-5

Introduction to the GPMC

Key Points
The GPMC is the hub for Group Policy management. However, it does not actually
manage the Group Policy settings within GPOs.
The GPMC also provides a COM interface to enable you to programmatically
access various GPO functions and features.

Question: Have you used the GPMC interface before?

Additional Reading:
For more information about GPMC, please see:
• Enterprise Management with the Group Policy Management Console
• Group Policy Management Console
• Group Policy Management Console Sample Scripts
• Group Policy Team Blog
10-6 Administering Group Policy in Windows PowerShell™

GPMC COM API

Key Points
The GPMC is a graphical user interface (GUI) console. It also comes with an API
that is based on COM. This GPMC COM API enables many of the features of
GPMC to be accessed programmatically for interactive use in scripts or custom
applications. Windows PowerShell can use this GPMC COM API.
The general approach to using the GPMC API is similar to using other COM-based
objects, but it is a bit different than using .NET or WMI. In most of the samples,
you will see three regular sets of operations:
• Getting the root object:
$gpm = new-object -comobject GPMgmt.GPM
• Getting GPMC constants:
$constants = $gpm.getconstants()
• Getting the domain object:
$dom = $gpm.getdomain("domain", "", "")

Question: Where would you look for more information on using the GPMC
interface with Windows PowerShell?
Administering Group Policy in Windows PowerShell™ Using COM 10-7

Additional Reading:
For additional information about the GPMC COM API, please see GPMC Object
Model.
10-8 Administering Group Policy in Windows PowerShell™

Demonstration: Creating a GPO

Question: When are you likely to use Starter GPOs?

Additional Reading:
For additional information about creating GPOs using
Windows PowerShell, please see CreateGPO Method of the IGPMDomain Interface
Administering Group Policy in Windows PowerShell™ Using COM 10-9

Discovering Modified GPOs

Key Points
Using the domain object (derived from the GPM base object), you can use the
SearchGPOs method to get a list of all GPOs or those that match certain criteria.
In addition to using the SearchGPOs method, you can use the filtering
mechanisms in Windows PowerShell (for example, if, where__) to select certain
GPOs for processing. For example, you can discover which GPOs have changed in
the past day.

Question: Can you also search Starter GPOs using the same method?
10-10 Administering Group Policy in Windows PowerShell™

Copying Settings from One GPO to Another

Key Points
You can use the GPMC COM interface to create a new GPO, either from an existing
GPO or from a Starter GPO. To create a new GPO that is a copy of an existing
GPO:
• Instantiate the $gpm root object, domain object, and constants.
• Find the target GPO using Get-GPO.
• Use the CopyTo method on the source GPO, specifying the domain and the
display name of the new GPO.

Question: Which naming conventions would you implement to make GPO


management easier?
Administering Group Policy in Windows PowerShell™ Using COM 10-11

Lesson 2
Managing Group Policy Objects

This lesson examines some administrative functions that you can perform using
the GPO COM interface and Windows PowerShell. These tasks include searching
for GPOs and backing up and restoring GPOs.
10-12 Administering Group Policy in Windows PowerShell™

Searching for GPOs

Key Points
The GPMC COM interface implements a searching mechanism that works as
follows:
• Derive the standard structures ($gpm, constants).
• Derive a search criteria object from the $gpm object.
• Add any required criteria to these search criteria (for example, to search for a
specific GPO) using constants to describe the specific criterion.
• Call the appropriate Search method to find the GPO.

Note: Starter GPOs are not enabled by default. You enable them by using the
GPMC GUI.

Question: What is returned from the Search method?


Administering Group Policy in Windows PowerShell™ Using COM 10-13

Backing Up GPOs

Key Points
On the GPM COM interface, you can back up GPOs one at a time by using the
Backup method of a GPO object. If you want to back up multiple GPOs, you must
call Backup() multiple times.
To back up a GPO, you must first get the GPO object that relates to the GPO that
you want to back up. Then use the Backup method of the GPO to perform backup
and check results.

Question: How often should you perform GPO backups?


10-14 Administering Group Policy in Windows PowerShell™

Restoring GPOs

Key Points
In some ways, restoring a GPO is similar to backing up a GPO. You first search for
the GPO, then restore a single GPO at a time via a collection object.

Question: Where should you store backup GPOs so that you can restore
them easily?
Administering Group Policy in Windows PowerShell™ Using COM 10-15

Lesson 3
Reporting Group Policy

This lesson looks at reporting with GPOs, including RSOP. This ability helps
administrators to develop reports on GPOS in their environment,
10-16 Administering Group Policy in Windows PowerShell™

Resultant Set of Policy

Key Points
Resultant Set of Policy (RSoP) is what happens when policy is applied, including
dealing with:
• Local/Site/Domain/OUs
• Multiple policies
• Loopback

RSoP has two modes.

Most RSoP work is done from the GUI. You can call RSoP from Windows
PowerShell but it is easier via GUI.

Question: When would you use RSoP?


Administering Group Policy in Windows PowerShell™ Using COM 10-17

Generating HTML Reports

Key Points
The GPMC interface provides some good reporting. You can report to XML or to
HTML. You can use these reporting interfaces to create reports as needed. For
example:

Foreach ($gpo in $gpos) {


$result=$gpo.GenerateReport($k.ReportHTML)
$x=$result.result
}

# Create output of last one


$x | set-content outgpo.html

# View it
& .\outgpo.html

Question: Do you use these HTML reports?


10-18 Administering Group Policy in Windows PowerShell™

Lab: Administering Group Policy in Windows


PowerShell

Exercise 1: Retrieving a GPO by Using a COM Object


Scenario
You are a directory administrator for Woodgrove Bank. You need to use Windows
PowerShell to retrieve a Group Policy object (GPO) from Active Directory so that
you can perform several management tasks that use the GPO.

Exercise Overview
In this exercise, you will use COM objects in Windows PowerShell.
The main tasks for this exercise are as follows:
1. Start the 6434A-NYC-DC1 virtual machine and log on as Administrator.
2. Retrieve the GPO that has the display name GPO1, and store it in a variable.
Administering Group Policy in Windows PowerShell™ Using COM 10-19

f Task 1: Start the 6434A-NYC-DC1 virtual machine and log on as


Administrator
• Start the 6434A-NYC-DC1 virtual machine and log on as Administrator using
the password Pa$$w0rd.
• Open Windows PowerShell.

f Task 2: Retrieve the GPO that has the display name GPO1, and store it
in a variable
• Instantiate the GPMC COM object.
• Retrieve a reference to the woodgrovebank.com domain.
• Create GPO search criteria and retrieve all GPOs in the domain.
• Use the Where-Object cmdlet to filter out all GPOs except the one that has the
display name "GPO1".
• Store the GPO in a variable named $gpo.

Results: After this exercise, you should have retrieved the GPO named GPO1 and
stored it in the variable $gpo.

Exercise 2: Copying Group Policy Settings


Scenario
You are a directory administrator for Woodgrove Bank. You need to make a copy
of an existing GPO to form the basis for a new GPO. This approach is typically
used when a department needs settings that are similar to those of another
department that already has a useful GPO, but linking is not appropriate because
the two departments need to maintain different policy settings throughout their life
cycle.

Exercise Overview
In this exercise, students will copy Group Policy settings from one GPO to another.
The main tasks for this exercise are as follows:
1. Copy the Group Policy object GPO1 to GPO3.
10-20 Administering Group Policy in Windows PowerShell™

f Task 1: Copy the Group Policy object GPO1 to GPO3.


• Copy GPO1 to a new GPO named GPO3. Use the CopyTo() method of the
$gpo object, and use the $domain object as a target.

Results: After this exercise, you should have copied GPO1 to GPO3.

Exercise 3: Backing Up and Restoring a GPO


Scenario
You are a directory administrator for Woodgrove Bank. You need to back up a
GPO, and test your ability to restore it. You use this feature most often to move
GPOs back and forth from your test environment to your production environment.

Exercise Overview
In this exercise, students will back up and restore GPOs.
The main tasks for this exercise are as follows:
1. Back up the GPO1 GPO.
2. Delete the GPO1 GPO.
3. Restore the GPO1 GPO.

f Task 1: Back up the GPO1 GPO


• Create a folder named C:\GPOBackup.
• Use the Backup() method of the $gpo object to back up GPO1 to a file named
GPO1Backup.

f Task 2: Delete the GPO1 GPO


• Use the GPMC to delete the GPO1 GPO, which is linked to the Tellers OU.
Administering Group Policy in Windows PowerShell™ Using COM 10-21

f Task 3: Restore the GPO1 GPO


• Obtain a reference to the GPOBackup folder.
• Use the SearchBackups() method to load all backed-up GPOs.
• Use the Where-Object cmdlet to filter out all GPOs that do not have a
GPODisplayName property of GPO1. Store the remaining GPO in a variable
named $backup.
• Use the RestoreGPO() method of the domain to restore the $backup object.

Results: After this exercise, you should have backed up, deleted, and restored a GPO.

Exercise 4: Generating Group Policy Reports


Scenario
You are a directory administrator for Woodgrove Bank. You need to restore a GPO,
but prior to doing so you need to generate a report describing the contents of the
GPO. You want the report to be in HTML format.

Exercise Overview
In this exercise, you will generate Group Policy change reports.
The main tasks for this exercise are as follows:
1. Create an HTML report of the backed-up GPO named GPO1.

f Task 1: Create an HTML report of the backed-up GPO named GPO1


• Use the GenerateReport() method of the $backup object to generate an
HTML report named GPO1.html.
• View the report in Internet Explorer.

Results: After this exercise, you should have viewed an HTML report of a backed-up
GPO.
10-22 Administering Group Policy in Windows PowerShell™

Lab Review
Administering Group Policy in Windows PowerShell™ Using COM 10-23

Module Review and Takeaways

Review Questions
1. What would you use Windows PowerShell for in terms of managing GPOs?
2. Why do you need the GPMC constants?
3. Which tools should you use to manage Group Policy settings?

Common Issues related to Group Policy


Identify the causes for the following common issues related to Group Policy and
fill in the troubleshooting tips. For answers, refer to relevant lessons in the module.

Issue Troubleshooting tip

You are not able to access the


GPmgmt.GPM object.

Writing scripts results in a large


number of error messages.

The GPMC object is not like other


Windows PowerShell scripting.
10-24 Administering Group Policy in Windows PowerShell™

Best Practices related to Group Policy


• Have a good naming strategy.
• Build some simple functions (get-GPO, etc) and place them in your
$profile file.
• Test your scripts very carefully.
• Then test them again

Tools

Tool Use for Where to find it


GPMC Managing Group Policy Administrative Tools

GPMC API Scripting and automating group Windows PowerShell


policy administration
Administering Group Policy in Windows PowerShell™ Using COM 10-25

Course Evaluation

Your evaluation of this course will help Microsoft understand the quality of your
learning experience.
Please work with your training provider to access the course evaluation form.
Microsoft will keep your answers to this survey private and confidential and will
use your responses to improve your future learning experience. Your open and
honest feedback is valuable and appreciated.

Potrebbero piacerti anche