6434 Automating Windows Server 2008 Administration With Windows PowerShell
6434 Automating Windows Server 2008 Administration With Windows PowerShell
6434A
Automating Windows Server 2008 ®
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.
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 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
Lesson 1
Introduction to 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
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™
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
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.
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
Key Points
Windows PowerShell can be extended with:
• Providers
• Cmdlets
• Scripts, functions, aliases
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
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.
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
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™
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
Question: How would you run Windows PowerShell from a logon script?
1-16 Introduction to 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
Results: After this exercise, you should have installed Windows PowerShell on
6434A-NYC-DC1.
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™
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™
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?
Tools
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
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”
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: What information does Get-Member show for the processes in this
demonstration?
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™
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.
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™
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
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?
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
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™
Question: Do you foresee any problems with using the tab expansion feature of
Windows PowerShell?
Overview of Windows PowerShell™ 2-19
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)
Question: Which aliases can you use to facilitate tasks on your job?
Overview of Windows PowerShell™ 2-21
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™
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
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).
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
Results: After this exercise, you should have identified two cmdlets and created an
alias for one of those cmdlets.
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.
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™
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?
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
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.
Tools
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
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.
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.
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
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
Key Points
Measure-Object has several parameters that govern which calculations to perform
on its input objects.
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
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?
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.
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
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.
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.
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
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.
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
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
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
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”
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
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
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
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
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
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 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.
Results: After this exercise, you should have displayed various memory utilization
statistics for the processes running on a computer.
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
Results: After this exercise, you should have created an associative array and displayed
specific values from within the array.
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
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
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
Tools
Get-ChildItem cmdlet Listing the files and folders in the Windows PowerShell
current location
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
Lesson 1
Managing Windows® Processes with
Windows PowerShell
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
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.
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
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).
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
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.
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.
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
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.
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
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
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 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.
Results: After this exercise, you should have produced various strings that include
formatted data.
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
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
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
Tools
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
Lesson 1
Writing Windows PowerShell Scripts
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.
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™
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
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
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.
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
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.
Lesson 3
Security in Windows PowerShell
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.
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.
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.
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
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: 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
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
Question: How would you determine which shell you are in?
5-24 Introduction to Scripting with Windows PowerShell™
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
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™
Results: After this exercise, you should have created a script which, when executed,
displays information about processes running on the server.
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.
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
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™
Tools .
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
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
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
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
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.
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
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
Lesson 2
Iteration Flow Control
Question: How are the foreach construct and the ForEach-Object cmdlet similar?
How are they different?
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
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
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
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.
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.
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.
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
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.
Question: When would you need to run a script in the local scope?
Implementing Flow Control and Functions 6-21
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
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
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 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
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 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.
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
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
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.
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
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
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.
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?
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
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
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
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.
Additional Reading:
For more information on accessing the registry, see Navigating Windows
PowerShell.
7-12 Working with Files, the Registry, and Certificate Stores
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
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: Would you use a different technique to create a new registry value or
subkey?
7-14 Working with Files, the Registry, and 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
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
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
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
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
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: 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
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
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
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: 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
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.
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
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
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 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
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 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
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 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
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 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
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
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
• 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
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
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
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
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
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
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:
Or as follows:
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
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
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
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).
Key Points
The Win32_Volume class contains two useful methods:
• DefragAnalysis
• Defrag
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
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
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.
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
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
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
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
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: Which properties and methods does WMI implement for shared
folders?
Managing the Windows Operating System Using Windows PowerShell™ and WMI 8-21
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
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.
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
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: 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
Key Points
You can use the Get-WMIObject cmdlet to get a list of WMI classes (use the List
parameter).
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
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
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
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
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
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.
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 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.
Results: After this exercise, you should have created a new shared folder and launched
Windows Notepad.
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.
Results: After this exercise, you should have produced drive volume reports that can
be used for inventory and capacity planning purposes.
Exercise Overview
The main tasks for this exercise are as follows:
1. Defragment the E drive.
Results: After this exercise, you should have defragmented the E drive on your virtual
machine.
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.
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
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
Tools
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.
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
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.
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™
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™
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.
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
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™
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
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™
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™
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
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™
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
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™
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™
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
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.
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™
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.
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 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 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 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.
Results: After this exercise, you should have updated two user accounts to have a new
manager attribute.
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
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?
Tools
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™
Key Points
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.
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.
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™
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™
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
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™
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.
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™
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.
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.
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™
Key Points
Resultant Set of Policy (RSoP) is what happens when policy is applied, including
dealing with:
• Local/Site/Domain/OUs
• Multiple policies
• Loopback
Most RSoP work is done from the GUI. You can call RSoP from Windows
PowerShell but it is easier via GUI.
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:
# View it
& .\outgpo.html
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 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 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™
Results: After this exercise, you should have copied GPO1 to GPO3.
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.
Results: After this exercise, you should have backed up, deleted, and restored a GPO.
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.
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
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?
Tools
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.