Documente Academic
Documente Profesional
Documente Cultură
LEARNING
PRODUCT
6434A
Automating Windows Server 2008
Administration with Windows
PowerShell
TM
OFFICIAL
Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, place or event is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part
of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted
in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for
any purpose, without the express written permission of Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
The names of manufacturers, products, or URLs are provided for informational purposes only and
Microsoft makes no representations and warranties, either expressed, implied, or statutory,
regarding these manufacturers or the use of the products with any Microsoft technologies. The
inclusion of a manufacturer or product does not imply endorsement of Microsoft of the
manufacturer or product. Links may be provided to third party sites. Such sites are not under the
control of Microsoft and Microsoft is not responsible for the contents of any linked site or any link
contained in a linked site, or any changes or updates to such sites. Microsoft is not responsible for
webcasting or any other form of transmission received from any linked site. Microsoft is providing
these links to you only as a convenience, and the inclusion of any link does not imply endorsement
of Microsoft of the site or the products contained therein.
2008 Microsoft Corporation. All rights reserved.
Microsoft, and Windows are either registered trademarks or trademarks of Microsoft Corporation in
the United States and/or other countries.
All other trademarks are property of their respective owners.
ii
These license terms are an agreement between Microsoft Corporation and you. Please read them. They
apply to the Licensed Content named above, which includes the media on which you received it, if any. The
terms also apply to any Microsoft
updates,
supplements,
support services
for this Licensed Content, unless other terms accompany those items. If so, those terms apply.
By using the Licensed Content, you accept these terms. If you do not accept them, do not use
the Licensed Content.
If you comply with these license terms, you have the rights below.
1. DEFINITIONS.
a. Academic Materials means the printed or electronic documentation such as manuals,
workbooks, white papers, press releases, datasheets, and FAQs which may be included in the
Licensed Content.
b. Authorized Learning Center(s) means a Microsoft Certified Partner for Learning Solutions
location, an IT Academy location, or such other entity as Microsoft may designate from time to time.
c. Authorized Training Session(s) means those training sessions authorized by Microsoft and
d. Course means one of the courses using Licensed Content offered by an Authorized Learning
Center during an Authorized Training Session, each of which provides training on a particular
Microsoft technology subject matter.
e. Device(s) means a single computer, device, workstation, terminal, or other digital electronic or
analog device.
f.
Licensed Content means the materials accompanying these license terms. The Licensed
Content may include, but is not limited to, the following elements: (i) Trainer Content, (ii) Student
Content, (iii) classroom setup guide, and (iv) Software. There are different and separate
components of the Licensed Content for each Course.
g.
Software means the Virtual Machines and Virtual Hard Disks, or other software applications that
may be included with the Licensed Content.
h. Student(s) means a student duly enrolled for an Authorized Training Session at your location.
Student Content means the learning materials accompanying these license terms that are for
use by Students and Trainers during an Authorized Training Session. Student Content may include
labs, simulations, and courseware files for a Course.
j.
Trainer(s) means a) a person who is duly certified by Microsoft as a Microsoft Certified Trainer
and b) such other individual as authorized in writing by Microsoft and has been engaged by an
Authorized Learning Center to teach or instruct an Authorized Training Session to Students on its
behalf.
k. Trainer Content means the materials accompanying these license terms that are for use by
i.
Trainers and Students, as applicable, solely during an Authorized Training Session. Trainer Content
may include Virtual Machines, Virtual Hard Disks, Microsoft PowerPoint files, instructor notes, and
demonstration guides and script files for a Course.
l.
Virtual Hard Disks means Microsoft Software that is comprised of virtualized hard disks (such as
a base virtual hard disk or differencing disks) for a Virtual Machine that can be loaded onto a single
computer or other device in order to allow end-users to run multiple operating systems concurrently.
For the purposes of these license terms, Virtual Hard Disks will be considered Trainer Content.
m. Virtual Machine means a virtualized computing experience, created and accessed using
Microsoft Virtual PC or Microsoft Virtual Server software that consists of a virtualized hardware
environment, one or more Virtual Hard Disks, and a configuration file setting the parameters of the
virtualized hardware environment (e.g., RAM). For the purposes of these license terms, Virtual Hard
Disks will be considered Trainer Content.
n.
you means the Authorized Learning Center or Trainer, as applicable, that has agreed to these
license terms.
2. OVERVIEW.
Licensed Content. The Licensed Content includes Software, Academic Materials (online and
electronic), Trainer Content, Student Content, classroom setup guide, and associated media.
License Model. The Licensed Content is licensed on a per copy per Authorized Learning Center
location or per Trainer basis.
a. Authorized Learning Centers and Trainers: For each Authorized Training Session, you
may:
i.
either install individual copies of the relevant Licensed Content on classroom Devices only for
use by Students enrolled in and the Trainer delivering the Authorized Training Session, provided
that the number of copies in use does not exceed the number of Students enrolled in and the
Trainer delivering the Authorized Training Session, OR
ii. install one copy of the relevant Licensed Content on a network server only for access by
classroom Devices and only for use by Students enrolled in and the Trainer delivering the
Authorized Training Session, provided that the number of Devices accessing the Licensed
Content on such server does not exceed the number of Students enrolled in and the Trainer
delivering the Authorized Training Session.
iii. and allow the Students enrolled in and the Trainer delivering the Authorized Training Session to
use the Licensed Content that you install in accordance with (ii) or (ii) above during such
Authorized Training Session in accordance with these license terms.
Separation of Components. The components of the Licensed Content are licensed as a single
unit. You may not separate the components and install them on different Devices.
i.
ii. Third Party Programs. The Licensed Content may contain third party programs. These license
terms will apply to the use of those third party programs, unless other terms accompany those
programs.
b. Trainers:
i.
Trainers may Use the Licensed Content that you install or that is installed by an Authorized
Learning Center on a classroom Device to deliver an Authorized Training Session.
ii. Trainers may also Use a copy of the Licensed Content as follows:
A. Licensed Device. The licensed Device is the Device on which you Use the Licensed Content.
You may install and Use one copy of the Licensed Content on the licensed Device solely for
your own personal training Use and for preparation of an Authorized Training Session.
B. Portable Device. You may install another copy on a portable device solely for your own
personal training Use and for preparation of an Authorized Training Session.
4. PRE-RELEASE VERSIONS. If this is a pre-release (beta) version, in addition to the other provisions
in this agreement, these terms also apply:
a. Pre-Release Licensed Content. This Licensed Content is a pre-release version. It may not
contain the same information and/or work the way a final version of the Licensed Content will. We
may change it for the final, commercial version. We also may not release a commercial version.
You will clearly and conspicuously inform any Students who participate in each Authorized Training
Session of the foregoing; and, that you or Microsoft are under no obligation to provide them with
any further content, including but not limited to the final released version of the Licensed Content
for the Course.
b. Feedback. If you agree to give feedback about the Licensed Content to Microsoft, you give to
Microsoft, without charge, the right to use, share and commercialize your feedback in any way and
for any purpose. You also give to third parties, without charge, any patent rights needed for their
products, technologies and services to use or interface with any specific parts of a Microsoft
software, Licensed Content, or service that includes the feedback. You will not give feedback that is
subject to a license that requires Microsoft to license its software or documentation to third parties
because we include your feedback in them. These rights survive this agreement.
c. Confidential Information. The Licensed Content, including any viewer, user interface, features
and documentation that may be included with the Licensed Content, is confidential and proprietary
to Microsoft and its suppliers.
i.
Use. For five years after installation of the Licensed Content or its commercial release,
whichever is first, you may not disclose confidential information to third parties. You may
disclose confidential information only to your employees and consultants who need to know
the information. You must have written agreements with them that protect the confidential
information at least as much as this agreement.
ii.
you received from a third party who did not breach confidentiality obligations to
Microsoft or its suppliers; or
protective order or otherwise protect the information. Confidential information does not
include information that
d.
Term. The term of this agreement for pre-release versions is (i) the date which Microsoft informs
you is the end date for using the beta version, or (ii) the commercial release of the final release
version of the Licensed Content, whichever is first (beta term).
e.
Use. You will cease using all copies of the beta version upon expiration or termination of the beta
term, and will destroy all copies of same in the possession or under your control and/or in the
possession or under the control of any Trainers who have received copies of the pre-released
version.
f.
Copies. Microsoft will inform Authorized Learning Centers if they may make copies of the beta
version (in either print and/or CD version) and distribute such copies to Students and/or Trainers. If
Microsoft allows such distribution, you will follow any additional terms that Microsoft provides to you
for such copies and distribution.
Software.
ii. Virtual Hard Disks. The Licensed Content may contain versions of Microsoft XP, Microsoft
Windows Vista, Windows Server 2003, Windows Server 2008, and Windows 2000 Advanced
Server and/or other Microsoft products which are provided in Virtual Hard Disks.
A. If the Virtual Hard Disks and the labs are launched through the Microsoft
Learning Lab Launcher, then these terms apply:
Time-Sensitive Software. If the Software is not reset, it will stop running based upon the
time indicated on the install of the Virtual Machines (between 30 and 500 days after you
install it). You will not receive notice before it stops running. You may not be able to
access data used or information saved with the Virtual Machines when it stops running and
may be forced to reset these Virtual Machines to their original state. You must remove the
Software from the Devices at the end of each Authorized Training Session and reinstall and
launch it prior to the beginning of the next Authorized Training Session.
B. If the Virtual Hard Disks require a product key to launch, then these terms
apply:
Microsoft will deactivate the operating system associated with each Virtual Hard Disk.
Before installing any Virtual Hard Disks on classroom Devices for use during an Authorized
Training Session, you will obtain from Microsoft a product key for the operating system
software for the Virtual Hard Disks and will activate such Software with Microsoft using such
product key.
C. These terms apply to all Virtual Machines and Virtual Hard Disks:
You may only use the Virtual Machines and Virtual Hard Disks if you comply with
the terms and conditions of this agreement and the following security
requirements:
o
You may not install Virtual Machines and Virtual Hard Disks on portable Devices or
Devices that are accessible to other networks.
You must remove Virtual Machines and Virtual Hard Disks from all classroom Devices at
the end of each Authorized Training Session, except those held at Microsoft Certified
Partners for Learning Solutions locations.
You must remove the differencing drive portions of the Virtual Hard Disks from all
classroom Devices at the end of each Authorized Training Session at Microsoft Certified
Partners for Learning Solutions locations.
You will ensure that the Virtual Machines and Virtual Hard Disks are not copied or
downloaded from Devices on which you installed them.
You will strictly comply with all Microsoft instructions relating to installation, use,
activation and deactivation, and security of Virtual Machines and Virtual Hard Disks.
You may not modify the Virtual Machines and Virtual Hard Disks or any contents
thereof.
You may not reproduce or redistribute the Virtual Machines or Virtual Hard Disks.
ii. Classroom Setup Guide. You will assure any Licensed Content installed for use during an
Authorized Training Session will be done in accordance with the classroom set-up guide for the
Course.
iii. Media Elements and Templates. You may allow Trainers and Students to use images, clip
art, animations, sounds, music, shapes, video clips and templates provided with the Licensed
Content solely in an Authorized Training Session. If Trainers have their own copy of the
Licensed Content, they may use Media Elements for their personal training use.
iv. iv Evaluation Software. Any Software that is included in the Student Content designated as
Evaluation Software may be used by Students solely for their personal training outside of the
Authorized Training Session.
b. Trainers Only:
i.
Use of PowerPoint Slide Deck Templates. The Trainer Content may include Microsoft
PowerPoint slide decks. Trainers may use, copy and modify the PowerPoint slide decks only for
providing an Authorized Training Session. If you elect to exercise the foregoing, you will agree
or ensure Trainer agrees: (a) that modification of the slide decks will not constitute creation of
obscene or scandalous works, as defined by federal law at the time the work is created; and
(b) to comply with all other terms and conditions of this agreement.
ii. Use of Instructional Components in Trainer Content. For each Authorized Training
Session, Trainers may customize and reproduce, in accordance with the MCT Agreement, those
portions of the Licensed Content that are logically associated with instruction of the Authorized
Training Session. If you elect to exercise the foregoing rights, you agree or ensure the Trainer
agrees: (a) that any of these customizations or reproductions will only be used for providing an
Authorized Training Session and (b) to comply with all other terms and conditions of this
agreement.
iii. Academic Materials. If the Licensed Content contains Academic Materials, you may copy and
use the Academic Materials. You may not make any modifications to the Academic Materials
and you may not print any book (either electronic or print version) in its entirety. If you
reproduce any Academic Materials, you agree that:
The use of the Academic Materials will be only for your personal reference or training use
You will not republish or post the Academic Materials on any network computer or
broadcast in any media;
You will include the Academic Materials original copyright notice, or a copyright notice to
Microsofts benefit in the format provided below:
Form of Notice:
2008 Reprinted for personal reference use only with permission by Microsoft
Corporation. All rights reserved.
Microsoft, Windows, and Windows Server are either registered trademarks or
trademarks of Microsoft Corporation in the US and/or other countries. Other
product and company names mentioned herein may be the trademarks of their
respective owners.
6. INTERNET-BASED SERVICES. Microsoft may provide Internet-based services with the Licensed
Content. It may change or cancel them at any time. You may not use these services in any way that
could harm them or impair anyone elses use of them. You may not use the services to try to gain
unauthorized access to any service, data, account or network by any means.
7. SCOPE OF LICENSE. The Licensed Content is licensed, not sold. This agreement only gives you some
rights to use the Licensed Content. Microsoft reserves all other rights. Unless applicable law gives you
more rights despite this limitation, you may use the Licensed Content only as expressly permitted in this
agreement. In doing so, you must comply with any technical limitations in the Licensed Content that
only allow you to use it in certain ways. You may not
install more copies of the Licensed Content on classroom Devices than the number of Students and
the Trainer in the Authorized Training Session;
allow more classroom Devices to access the server than the number of Students enrolled in and the
Trainer delivering the Authorized Training Session if the Licensed Content is installed on a network
server;
copy or reproduce the Licensed Content to any server or location for further reproduction or
distribution;
disclose the results of any benchmark tests of the Licensed Content to any third party without
Microsofts prior written approval;
reverse engineer, decompile or disassemble the Licensed Content, except and only to the extent
that applicable law expressly permits, despite this limitation;
make more copies of the Licensed Content than specified in this agreement or allowed by applicable
law, despite this limitation;
access or use any Licensed Content for which you (i) are not providing a Course and/or (ii) have not
been authorized by Microsoft to access and use;
use the Licensed Content for commercial hosting services or general business purposes.
Rights to access the server software that may be included with the Licensed Content, including the
Virtual Hard Disks does not give you any right to implement Microsoft patents or other Microsoft
intellectual property in software or devices that may access the server.
8. EXPORT RESTRICTIONS. The Licensed Content is subject to United States export laws and
regulations. You must comply with all domestic and international export laws and regulations that apply
to the Licensed Content. These laws include restrictions on destinations, end users and end use. For
additional information, see www.microsoft.com/exporting.
9. NOT FOR RESALE SOFTWARE/LICENSED CONTENT. You may not sell software or Licensed
Content marked as NFR or Not for Resale.
10. ACADEMIC EDITION. You must be a Qualified Educational User to use Licensed Content marked as
Academic Edition or AE. If you do not know whether you are a Qualified Educational User, visit
www.microsoft.com/education or contact the Microsoft affiliate serving your country.
11. TERMINATION. Without prejudice to any other rights, Microsoft may terminate this agreement if you
fail to comply with the terms and conditions of these license terms. In the event your status as an
Authorized Learning Center or Trainer a) expires, b) is voluntarily terminated by you, and/or c) is
terminated by Microsoft, this agreement shall automatically terminate. Upon any termination of this
agreement, you must destroy all copies of the Licensed Content and all of its component parts.
12. ENTIRE AGREEMENT. This agreement, and the terms for supplements, updates, Internet-
based services and support services that you use, are the entire agreement for the Licensed
Content and support services.
b. Outside the United States. If you acquired the Licensed Content in any other country, the laws
of that country apply.
14. LEGAL EFFECT. This agreement describes certain legal rights. You may have other rights under the
laws of your country. You may also have rights with respect to the party from whom you acquired the
Licensed Content. This agreement does not change your rights under the laws of your country if the
laws of your country do not permit it to do so.
15. DISCLAIMER OF WARRANTY. The Licensed Content is licensed as-is. You bear the risk of
using it. Microsoft gives no express warranties, guarantees or conditions. You may have
additional consumer rights under your local laws which this agreement cannot change. To
the extent permitted under your local laws, Microsoft excludes the implied warranties of
merchantability, fitness for a particular purpose and non-infringement.
Contents
Module 1: Introduction to Windows PowerShell
Lesson 1: Introduction to Windows PowerShell
1-3
1-10
1-16
2-3
2-9
2-16
2-22
2-28
3-3
3-9
3-15
3-21
3-25
4-3
4-9
4-16
xi
5-3
5-10
5-16
5-20
5-25
6-3
6-10
6-15
6-23
7-3
7-10
7-15
7-20
7-23
7-30
8-3
8-11
Lesson 3: Managing Shadow Copies Using Windows PowerShell with WMI 8-15
Lesson 4: Managing Shared Folders with Windows PowerShell
8-19
8-22
8-29
9-3
9-9
9-17
9-27
10-3
10-11
10-15
10-18
xii
xiii
Course Description
This course provides you with the knowledge and skills to utilize Windows
PowerShell for administering and automating administration of Windows Server
2008. The course focuses on cmdlets, script structure and flow control, language
syntax, and implementation details of scripting administrative tasks using COM,
WMI, and .NET foundations.
Audience
This course is intended for Windows administrators interested in automating
Windows Server 2008 administration tasks, as well as those people looking for a
full-featured interactive command-line environment for Windows operating
systems. Windows end users or developers who need to understand what is
involved in Windows administration or command-line environments may also find
this course helpful.
Student Prerequisites
This course requires that you meet the following prerequisites:
Course 2433: Microsoft Visual Basic Scripting Edition and Microsoft Windows
Script Host Essentials, or have equivalent knowledge of scripting and
automation in Windows.
Course Objectives
After completing this course, students will be able to:
Control the formatting of the resultant set of objects that are emitted at the end
of a pipeline
Implement flow control within scripts and define functions and filters to help
modularize complex scripts
Administer and maintain Active Directory directory services and IIS 7.0 Web
sites using Windows PowerShell
Course Outline
This section provides an outline of the course:
Module 1, "Introduction to Windows PowerShell" explains how to check your
system for prerequisites for Windows PowerShell, use Server Manager to install
Windows PowerShell architecture, confirm installation, and use Windows
PowerShell commands to customize the Windows PowerShell environment.
Module 2, "Overview of Windows PowerShell" explains basic concepts in
Windows PowerShell, including objects, variables, and cmdlets. It describes how to
invoke available cmdlets and aliases, assign aliases. The module also includes
demonstrations of tab expansion and basic operators.
Module 3, "Building Pipelines for Assembly-Line Style Processing" 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.
Module 4, "Managing Processes and Formatting Cmdlet Output" explains how to
choose a format in which to present data that is appropriate to the data set, format
specific process properties, such as memory usage or CPU time, and use custom
formatting. It also describes how you can view, start, and stop processes and
services.
Module 5, "Introduction to Scripting with Windows PowerShell" explains how to
write and modify scripts to perform a sequence of cmdlets. Security and working
with credentials are also discussed.
xiv
xv
Course Materials
The following materials are included with your kit:
Course Companion CD. The Course Companion CD contains the full course
content, including expanded content for each topic pages, full lab exercises
and answer keys, topical and categorized resources and Web links. The
demonstration script files and supporting script files used in the class are also
included on the Course Companion CD. This CD is meant to be used both
inside and outside of the class.
Note: To access the full course content, insert the Course Companion CD into the
CD-ROM drive, and then in the root directory of the CD, double-click StartCD.exe.
Course evaluation. At the end of the course, you will have the opportunity to
complete an online evaluation to provide feedback on the course, training
facility, and instructor.
xvi
xvii
Important: At the end of lab 1, if you close the virtual machine, be sure to save
changes. Saving changes will ensure that the Windows PowerShell installation that
you performed in the Module 1 lab persists in the virtual machine for use during the
labs for other modules. After each subsequent lab, make the choice to either retain
the changes for use during the remaining labs or, at your discretion, to abandon
changes made in each lab. In this course, you might find it useful to carry over
changes made in one lab to another. Therefore, it is recommended that you retain
your changes.
If you do not wish to retain such changes and you choose to abandon the changes
made in a lab, you must close the virtual machine and must not save any changes.
To close a virtual machine without saving the changes, perform the following steps:
1. On the virtual machine, on the Action menu, click Close.
2. In the Close dialog box, in the What do you want the virtual machine to do?
list, click Turn off and delete changes, and then click OK.
In this course, all lab exercises are performed on the 6434A-NYC-DC1 virtual
machine.
Software Configuration
The following software is installed on each VM:
Access the script files within the local Windows session of the student
computer. This approach can be useful for reading the scripts.
Note that the Start-Demo.ps1 script must be executed prior to running demo
scripts, because this script defines the Start-Demo function. The Start-Demo
function is not an intrinsic part of Windows PowerShell.
Additionally, many of the demo scripts assume that the supporting script files are
at the same location as the demo script. In either the host computer or the virtual
machine, it may be useful to copy all the demo scripts and supporting scripts to a
folder on the hard disk of each machine.
Classroom Setup
Each classroom computer will have the same virtual machine configured in the
same way.
xviii
xix
1-1
Module 1
Introduction to Windows PowerShell
Contents:
Lesson 1: Introduction to Windows PowerShell
1-3
1-10
1-16
Module Overview
1-2
Lesson 1
1-3
Key Points
In addition to being a scripting language and an interactive command shell,
Windows PowerShell is:
An extensive environment
1-4
1-5
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?
Key Points
Windows PowerShell uses Microsoft .NET Framework version 2.0 as a foundation.
.NET Framework 2.0 and Windows PowerShell run on:
Windows Vista
Windows XP
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
1-6
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.
Question: How can you take advantage of the object-oriented nature of
Windows PowerShell?
Key Points
The Windows operating system supports object-oriented frameworks other
than .NET; for example, COM and WMI.
You can use combinations of objects from .NET, COM, and WMI frameworks
interactively, and in scripts, within the Windows PowerShell environment.
Question: How can you combine .NET, COM, and WMI objects to facilitate
your tasks?
1-8
Key Points
Windows PowerShell can be extended with:
Providers
Cmdlets
1-9
Lesson 2
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.
1-10
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.
Question: Is your system a Full or a Server Core installation?
Key Points
Windows PowerShell is installed in the following path by default:
C:\Windows\System32\WindowsPowerShell\v1.0
Other files at this location include:
Pwrshmsg.dll
Pwrshsip.dll
1-12
1-13
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?
Question: Prior to changing the execution policy, could you have run scripts?
Question: After changing the execution policy, can you run some scripts?
1-14
1-15
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.
2.
3.
1-16
1-17
Make a note of the server operating system and architecture (x64 or x86).
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.
2.
Configure the console window to have a buffer width of 100 characters and a
physical width of 80 characters.
Configure the console window to have white text on a dark green background.
Feel free to change the colors to meet your personal preferences.
1-18
Lab Review
1-19
Review Questions
1.
2.
3.
4.
What are three kinds of objects that Windows PowerShell can work with?
Troubleshooting tip
1-20
1-21
2.
You are using a Windows PowerShell script to manage Windows Server 2008.
Your manager asks if your scripts can be used to manage Windows 2000
Server or Windows 2000 Professional.
Set the execution policy security level to RemoteSigned. This allows scripts
that are on the local computer to be run in Windows PowerShell, but requires
scripts that have been downloaded from remote locations to be signed with a
digital signature.
Tools
Tool
Use for
Where to find it
Get-ExecutionPolicy
Windows PowerShell
Set-ExecutionPolicy
Windows PowerShell
2-1
Module 2
Overview of Windows PowerShell
Contents:
Lesson 1: Overview of Objects
2-3
2-9
2-16
2-22
2-28
Module Overview
2-2
Lesson 1
Overview of Objects
You need a basic understanding of the nature of objects and classes in an objectbased or object-oriented environment to understand the possibilities with
Windows PowerShell.
2-3
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
2-4
2-5
Key Points
An object class is the definition of the rules for an object: which properties are
allowed. An object class is used as a template. All object instances reflect the class
definition. All objects of the same class share similar traits, behaviors, and even
perhaps some attribute values.
An object is specifically referred to as an object instance to further reinforce that
there might be many objects of a given class.
The object class can also have static methods, which provide additional features for
all instances of that class.
Question: Can you think of examples of computer-based object-oriented class
systems?
Question: Can you think of examples of classes or instances?
Question: What information does Get-Member show for the processes in this
demonstration?
Question: How can this information be useful?
2-6
2-7
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)?
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?
2-8
2-9
Lesson 2
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.
What Is a Cmdlet?
Key Points
Commandlets (cmdlets) are native Windows PowerShell commands. Each cmdlet
has a specific, typically small, task that it performs. Cmdlets are located in dynamic
link libraries (DLLs) known as snap-ins.
Windows PowerShell version 1.0 has over 130 built-in cmdlets. Extensions to
Windows PowerShell may include additional cmdlets.
Question: Which tasks would you like to perform with a cmdlet?
2-10
2-11
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?
Question: Which cmdlet can you use to obtain basic information about other
cmdlets, perhaps focusing on a particular noun or verb?
2-12
2-13
Question: Which cmdlet can you use to obtain detailed information about other
cmdlets and their parameters?
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-Process lists all processes by default, but when you give it a Name or Id
parameter, you can specify one or more names or process identifiers (comma
separated).
Get-Help provides information about cmdlets and other topics. Cmdlet names
can be used as parameters to Get-Help.
Question: What are some abbreviated cmdlets that you would use frequently?
Question: What is the shortest unique form of these abbreviated cmdlets?
2-14
2-15
Cmdlet Output
Key Points
Cmdlets can emit zero, one, or more objects.
If the output of a cmdlet is assigned to a variable, the objects are held in the
variable. Therefore, output is suppressed. Similarly, if an object emitted from one
cmdlet is sent down a pipeline, this output stays in object form.
To simplify the task of the administrator, the shell uses the default formatter to
convert the output objects to useful text.
Question: Can you come up with an analogy for this concept in other languages?
Lesson 3
2-16
Key Points:
Several features of Windows PowerShell help to make interactive administration
and script writing easier. These include:
Question: Which other features would you like to see in Windows PowerShell?
2-17
Question: Do you foresee any problems with using the tab expansion feature of
Windows PowerShell?
2-18
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)
2-20
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-21
Lesson 4
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.
2-22
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.
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
2-24
2-25
Key Points
Windows PowerShell supports many operators.
Question: What is the difference between the / and % operators, and what is their
relationship?
2-26
2-27
Assignment Operators
Key Points
Windows PowerShell supports several assignment operators.
The basic assignment operator is the equal sign (=), which simply takes the value
of the expression on the right of the equal sign and places the result in the variable
on the left of the equal sign.
Arithmetic assignment operators perform a binary operation on the initial value of
the variable on the left with the expression on the right, and then assign the result
to the variable on the left.
In Windows PowerShell, you can also specify the "++" or "--" at the beginning of the
variable name (for example, ++$count or --$airquality).
Question: What are some examples of practical uses of assignment operators in
Windows PowerShell?
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:
2-28
2-29
1.
2.
3.
Create an alias.
Identify the cmdlet that displays a list of Windows event log entries.
Create an alias named OF that references the cmdlet used to pipe output to a
specified text file.
Results: After this exercise, you should have identified two cmdlets and created an
alias for one of those cmdlets.
Exercise 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.
2.
Use the Get-Process cmdlet to retrieve the currently running processes. Store
the results of the cmdlet in a variable named $processes.
2-30
Lab Review
2-31
Review Questions
1.
2.
3.
4.
What are four features of Windows PowerShell that can help make interactive
administration and script writing easier?
Troubleshooting tip
Be sure to use quotation marks (") rather than
apostrophes (') when specifying string literals
in which you need to have variable and special
character value substitution occur.
2-32
Issue
2-33
Troubleshooting tip
2.
You need to understand more about the operators and language syntax in
Windows PowerShell.
Simply use a cmdlet or pipeline of cmdlets when the resultant objects are
intended to be displayed on the console.
Put the cmdlet (or pipeline) in parentheses when you need to refer to it as an
object. This is useful not only with the dot operator for member access, but
also when you are using the output of cmdlets in other expressions or as
parameters to other cmdlets.
Tools
Tool
Use for
Where to find it
Get-Command
Windows PowerShell
Get-Help
Windows PowerShell
Set-Variable
Windows PowerShell
Tool
Set-Alias
Use for
Assigning a value to an alias
Where to find it
Windows PowerShell
2-34
3-1
Module 3
Building Pipelines for Assembly-Line Style
Processing
Contents:
Lesson 1: Using Pipelines
3-3
3-9
3-15
3-21
3-25
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.
3-2
Lesson 1
Using Pipelines
3-3
What Is a Pipeline?
Key Points
You can use a pipeline to directly connect the output of the first cmdlet to the
input of the second cmdlet.
You do not need to create a temporary file. The flow of data through the pipeline
from one cmdlet to another is managed by the shell.
The information (data) flowing from one cmdlet to another via the pipeline is in
the form of objects.
Question: What is the advantage of using a pipeline?
3-4
3-5
Multistage Pipelines
Key Points
For more complex processing, you can chain together a series of cmdlets using a
sequence of pipes. For each stage of the pipeline, the output of one cmdlet is piped
into the input of the next cmdlet.
Question: Why would you use a multistage pipeline?
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?
3-6
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?
Key Points
Measure-Object has several parameters that govern which calculations to perform
on its input objects.
Question: Which calculations can the Measure-Object cmdlet perform?
3-8
3-9
Lesson 2
Using Arrays
Arrays can be used in many ways in their own right, but they can also be used with
pipeline processing.
Key Points
Scalars represent one value. Literals, expressions, and variables can all be scalars,
and are scalar in cases when they represent, evaluate to, or hold one value.
Arrays can hold lists of basic values or lists of complex objects. Arrays can be used
to represent a collection of objects that is a result of one cmdlet or function.
Question: Can you think of some uses for arrays? What could they hold?
Question: How would values be put into an array?
Question: How would these values be referred to later?
Additional Reading:
For more information about the @() notation, see Windows PowerShell: Array
Literals in PowerShell
3-10
3-11
Associative Arrays
Key Points
Whereas basic arrays, are integer-indexed, associative arrays are indexed by name,
Each name is associated with a value. An empty associative array is specified as @{}.
Associative array indexes are keys that must be unique. Instead of using unique
integers, unique names are used.
Each value of an associative array consists of a key and a value separated by an
equal sign. If the name of the key includes spaces, the name must be quoted. If the
value is not numeric, but is a string value, it also should be quoted. Specify
multiple key/value pairs in the @{} set, with the semicolon separating each pair.
Question: What is the difference between an integer-indexed array and an
associative array?
Additional Reading:
For more information about collections and hash tables, see:
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?
3-12
3-13
Array Operators
Key Points
Arrays can be added using the addition (plus sign) + operator. The plus equal (+=)
operator can also be used to add to an array.
Individual values of arrays are referred to by index. Subsets of arrays can be
extracted by referring to a range or list of values.
Question: How would you add two arrays together?
Key Points
The dot operator can be used to refer to a member of an associative array. This
operator is similar to the property operator for objects.
Question: How is using the dot operator to access a member of an associative
array similar to using the dot operator to access a property of an object?
3-14
3-15
Lesson 3
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.
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:
3-16
3-17
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?
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?
3-18
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?
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:
3-20
3-21
Lesson 4
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.
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?
3-22
3-23
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?
3-24
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:
1.
2.
Use Windows PowerShell to display all the properties for a Process object.
Examine the list of Process object properties to determine the properties that
represent the following aspects of the process:
Results: After this exercise, you should have discovered the Process object properties
that represent the virtual memory utilization, paged memory utilization, and nonpaged memory utilization of a process.
3-26
3-27
Exercise Overview
In this exercise, you will use Windows PowerShell to calculate the memory usage
for the processes running on a computer.
The main tasks for this exercise are as follows:
1.
Display the average, total, minimum, and maximum values for virtual and
paged memory utilization by all running processes.
Results: After this exercise, you should have displayed various memory utilization
statistics for the processes running on a computer.
Exercise Overview
In this exercise you will create and utilize an associative array.
The main tasks for this exercise are as follows:
1.
2.
Create an associative array and store it in a variable named $arr. Populate the
array with the following key/value pairs:
Name/Server2
IP/192.168.10.10
Using the variable $arr created in Task 1, display only the value for the IP key.
Results: After this exercise, you should have created an associative array and displayed
specific values from within the array.
Exercise 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.
2.
3-28
3.
3-29
Use the Get-Process cmdlet to retrieve all running processes. Sort them so that
the processes using the most paged memory are displayed first.
Use the Get-Process cmdlet to retrieve all running processes. Sort them so that
the processes using the most paged memory are displayed first. Format the
output so that it is displayed as a table that includes only the names of the
processes and paged memory utilization.
Use the Get-Process cmdlet to retrieve all running processes. Sort them so that
the processes using the most paged memory are displayed first. Format the
output so that it is displayed as a table that includes only the names of the
processes and paged memory utilization. Display only the first 10 processes.
Results: After this exercise, you should have created a table that displays a sorted
subset of running processes.
Lab Review
3-30
3-31
Review Questions
1.
2.
What is the name of the Windows PowerShell software module that manages
the pipeline connections between cmdlets?
3.
4.
5.
6.
Troubleshooting tip
You need a report of the top consumers of virtual memory and RAM on a
server.
2.
Use arrays and the range operator to simplify iteration through a number of
values.
2.
Use the foreach construct for iterating through an array, but use the
ForEach-Object cmdlet for iterating through a pipeline.
3.
4.
3-32
3-33
Tools
Tool
Use for
Where to find it
Where-Object cmdlet
Windows PowerShell
ForEach-Object cmdlet
Windows PowerShell
Foreach construct
Windows PowerShell
Sort-Object cmdlet
Windows PowerShell
Select-Object cmdlet
Windows PowerShell
Measure-Object cmdlet
Windows PowerShell
Get-Process cmdlet
Windows PowerShell
Get-ChildItem cmdlet
Windows PowerShell
Get-Member cmdlet
Windows PowerShell
Get-Command cmdlet
Listing cmdlets.
Windows PowerShell
4-1
Module 4
Managing Processes and Formatting Cmdlet
Output
Contents:
Lesson 1: Managing Windows Processes with Windows PowerShell
4-3
4-9
4-16
Module Overview
4-2
Lesson 1
4-3
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?
4-4
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-5
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?
4-6
Launching Processes
Key Points
Processes can be launched using any classic Windows approach. You can start a
process simply by typing its file name at a Windows PowerShell prompt.
You can use Invoke-Item to open a file using file extension activation.
The static method [System.Diagnostics.Process]::Start supports several
arguments for running processes.
Question: How would you launch a process using alternate credentials?
4-7
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?
4-8
4-9
Lesson 2
Key Points
If objects are left in the pipeline, then Windows PowerShell uses the default
formatter to create output. Windows PowerShell pipes all remaining objects to the
Out-Default cmdlet by default
You can also specify a specific formatter and format by piping objects to the
format-* cmdlets (for example, Format-Table and Format-List).
Question: Which default formatter is used with information retrieved
by Get-Process?
Question: Where does the output go by default?
4-10
4-11
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?
Key Points
Windows PowerShell first uses a built-in XML display specification to format an
object. If a default view is not specified in the XML display, Windows PowerShell
looks at the number of properties to be displayed. It then chooses between the
Format-Table and Format-List cmdlets, depending on the number of properties to
format.
You can explicitly choose which output format Windows PowerShell should use,
including Format-Table, Format-List, Format-Wide, or Format-Custom. Simply add
the specific formatter explicitly at the end of the pipeline.
Question: Which type of output is most suited to Format-Table and Format-List?
Question: When would you use Format-Wide and Format-Custom?
4-12
4-13
Key Points
The formatting cmdlets perform the following functions:
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.
Question: Which of the four functions of the Select-Object cmdlet would be the
most useful on your job?
4-14
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.
Question: How would you format a number using the -f operator?
Additional Reading:
For more information about the .NET format operator notation, see .NET Format
String 101. The examples are specified using C#, but you can translate them to
Windows PowerShell for your own use.
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.
2.
4-16
3.
4.
4-17
2.
Display a list of installed services in a table, so that the table includes columns
only for the name and current status (running or stopped) of the services. The
table should not span the width of the Windows PowerShell window.
Display a list of installed services in a table, so that the table includes columns
only for the name, current status (running or stopped) services, and whether
or not the service can be paused.
Display the 20 most recent System event log entries in a list. The list should
include all properties of the event log entry objects.
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.
2.
3.
Retrieve all running processes and store them in a variable named $processes.
Use the -f operator to display the string, "The second process is x," so that "x" is
the name of the second process in $processes.
Use the -f operator to display the string, "The second process is x, and it is
using y bytes of virtual memory," so that "x" is the name of the second process
in $processes, and "y" is the amount of virtual memory being used by that
process.
Retrieve all running processes and store them in a variable named $processes.
Use the -f operator to display the string, "The second process is x, and it is
using yMB of virtual memory," so that "x" is the name of the second process in
$processes, and "y" is the amount of virtual memory being used by that
4-18
4-19
Use the Get-Date cmdlet to retrieve the current date and store it in a variable
named $now.
Display the string, "Today is x," where "x" is the current date formatted as a
short date (such as MM/DD/YYYY or DD/MM/YYYY, depending on the
regional settings of your computer).
Results: After this exercise, you should have produced various strings that include
formatted data.
Exercise 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.
2.
Use the -f operator to display the virtual memory utilization of the first process
in $processes. The virtual memory utilization should be displayed in
megabytes, using numeric formatting, with no digits after the decimal point.
Display a list of all running processes in a table that includes the names of the
processes and their virtual memory utilization. The virtual memory utilization
should be displayed in megabytes, using numeric formatting, with no digits
after the decimal point.
Results: After this exercise, you should have created a table that uses a calculated
column.
4-20
Lab Review
4-21
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.
4.
5.
4-22
4-23
Troubleshooting tip
2.
You need to apply an update, hot fix, or service pack to some of your servers.
One of the changes identified by a particular hot fix is that some DLL files are
updated. In order to determine which software and services on your servers
will potentially be impacted by this change, you need to list the services that
are using a particular DLL. How would you find the services using a given DLL
using Windows PowerShell?
3.
In monitoring your servers, you find that a particular user is consistently over
quota every week. In the past you have noted that this user often downloads
large files to his Documents folder subtree and then forgets to delete them.
You need to find the 15 biggest files in a folder as an automated task. How
would you implement the part of this task which finds the 15 biggest files in a
folder or folder subtree?
Use .NET format strings with the -f operator to simplify complex processing of
output formats.
Tools
Tool
Use for
Where to find it
Select-Object
Windows PowerShell
Sort-Object
Windows PowerShell
Format-Wide
Windows PowerShell
Format-List
Windows PowerShell
Format-Table
Windows PowerShell
4-24
5-1
Module 5
Introduction to Scripting with Windows
PowerShell
Contents:
Lesson 1: Writing Windows PowerShell Scripts
5-3
5-10
5-16
5-20
5-25
Module Overview
5-2
5-3
Lesson 1
What Is a Script?
Key Points
A Windows PowerShell script is a sequence of Windows PowerShell statements
that is saved as a file with a .ps1 extension. You can run a script the same way that
you would run a cmdlet, with or without parameters.
You can run a script from within Windows PowerShell by specifying either its full
or its relative path.
Question: Which statements would you put into a script file?
5-4
5-5
Key Points:
Separate output channels exist for:
The standard output of a script is the value of the script. The value of the script is
made up of a combination of:
Question: Can you think of a situation where you would need to write an object to
a pipeline?
5-6
5-7
Additional Reading:
For more information on converting VBScript to Windows PowerShell, see:
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?
5-8
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.
5-10
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.
Question: Which type of comments are useful to include in a script?
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?
5-12
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.
Question: What is an advantage of using a named parameter block instead of
simply processing parameters using the argument array?
5-14
5-15
Lesson 3
5-16
5-17
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:
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.
5-18
5-19
Key Points
The Get-Credential cmdlet prompts you for a user name and a password using a
Windows dialog box designed for fetching such credentials. You can also pass the
user name (which can include a domain) as a parameter to Get-Credential to
simplify user input.. Get-Credential returns a PSCredential object, which you can
use on other cmdlets, such as Get-WMIObject, to pass credentials. Not all cmdlets
support credentials.
Question: How can credentials be used to access resources on another computer?
Lesson 4
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.
5-20
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: Which scripts would be good to run automatically on
Windows PowerShell?
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?
5-22
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
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?
5-24
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.
2.
3.
4.
Add the Windows PowerShell command that will display the currently
running processes in a table format, so that only the name, physical memory
utilization, and virtual memory utilization of the process are displayed. The
table columns should not have excess blank space between them.
5-26
5-27
Exercise Overview
In this exercise you will create a Windows PowerShell profile and configure it to
automatically create aliases each time that the shell is opened.
The main tasks for this exercise are as follows:
1.
2.
3.
To the profile that you created, add the command that creates an alias named
Gel for the cmdlet Get-EventLog.
To the profile you created, add the command that creates an alias named Of
for the cmdlet Out-File.
Run Gel Security and ensure that the security event log entries are displayed.
Lab Review
5-28
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-29
Troubleshooting tip
You manage Web servers at a marketing firm. Two members of your team, Joe
and Ellen, are integrating scripts that you have successfully developed and
used into their site management tools. Your team sets up a private Web site
where you post the scripts that you are sharing. Joe and Ellen download your
scripts and use them in their framework. What recommendations do you have
for script security so that Ellen and Joe can run your scripts successfully?
5-30
5-31
Include comments within scripts that describe the intended use of the script
along with author and revision history. Do this even for scripts that you plan
to use only twice because scripts can evolve and last longer than initially
expected.
Tools .
Tool
Use for
Where to find it
Get-ExecutionPolicy
Windows PowerShell
Set-ExecutionPolicy
Windows PowerShell
SetAuthenticodeSignature
Windows PowerShell
5-32
6-1
Module 6
Implementing Flow Control and Functions
Contents:
Lesson 1: Controlling the Flow of Execution Within Scripts
6-3
6-10
6-15
6-23
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.
6-2
6-3
Lesson 1
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.
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.
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?
6-4
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.
Type matching: The type matching operators -is and -isnot enable a value to
be compared against a data type.
Question: Which operator would you use to see if a value is at or beyond a certain
value?
6-6
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?
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.
6-8
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 involves looking at a collection of objects one at a time. The ForEachObject cmdlet in Windows PowerShell enables you to iterate through objects in a
pipeline and objects in an array.
Windows PowerShell also provides additional constructs for iteration flow control
that are similar to the flow control mechanisms that you might have seen in other
programming languages.
This lesson presents the for and while constructs along with a discussion of break,
continue, and return in the context of flow control constructs.
6-10
6-11
Question: How are the foreach construct and the ForEach-Object cmdlet similar?
How are they different?
Question: What type of data does each iterate through?
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.
Question: Can you think of scenarios at your workplace when you would use one
of these constructs?
6-12
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?
Question: Can you think of a situation where the for construct would be more
useful than the while construct?
6-14
6-15
Lesson 3
What Is a Function?
Key Points
A function is a definition of a code block with a name. Functions are, therefore,
similar to scripts, but they can be loaded in random access memory (RAM) after
they are defined. One or more functions can be defined within a script.
Functions can support arguments, but the arguments can be declared, typed, and
initialized.
The scope of functions is identical to the scope of variables. A function that is
defined inside another function or another script is lost when that script or
function completes execution.
Question: How is a function different from a script?
6-16
6-17
Key Points
A filter is a function that either is declared with the filter keyword (instead of
function) or has a PROCESS block defined.
Filters can have three code blocks defined:
BEGIN
PROCESS
END
Functions wait for all input coming down the pipeline to be accumulated before
they begin processing. The $input variable is used to process all input.
Question: How is a filter different from a function?
Key Points
Function and filter parameters are loosely bound. Use the $args array and
$args.count to address them.
You can name parameters. You can declare parameters with specific data types.
You can initialize default values for parameters so that if a caller does not supply a
certain parameter, a default value is assumed.
Question: What is the benefit of using named parameters?
Additional Reading:
For more information about using parameters in Windows PowerShell, see
Windows PowerShell: Next Generation Command Line Scripting by Jeffrey Snover.
6-18
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.
6-20
Question: In the current environment, how would you declare variable and
function definitions that are not defined with global scope in a script?
6-21
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?
6-22
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.
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 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
6-24
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.
2.
The contents of the function should use the $computer input argument
rather than the $computer variable previously defined in the script.
The function should return its output rather than writing it to the console
window.
6-26
Lab Review
6-27
Review Questions
1.
What are the four parts of a for construct besides the for keyword and
punctuation?
2.
3.
4.
5.
6-28
6-29
Troubleshooting tip
You have several Windows PowerShell scripts that you and your colleagues
have developed in-house. Now you install a package of scripts that you have
purchased or acquired for monitoring disk, folder, and network share usage
on your servers and workstations. Over the next few weeks you notice that
some of your scripts are not working correctly. One example is a function
called Update-Statistics that your organization developed and uses for
tracking Web site and blog updates and access. Upon investigation, you find
that the disk monitoring package that you downloaded also has a function
called Update-Statistics, which is used internally but defined with global
scope.
2.
Utilize existing scripts, functions, and filters that have been developed
by the team
Think modularly when you are writing scripts. Although not as rigorous as
large-scale software development, script writing can benefit from at least a few
moments of thoughtful design. If you find that scripts are doing too many
things, consider breaking different parts into functions. When this process is
performed logically, there can be many benefits. Also, if you realize that an
initial version of a script fetches data, processes the data, and formats the
output, consider defining a filter (or more than one) to handle the core part of
the processing. Then use a pipeline to fetch the data and send it to the filter.
You can also code fetching and filtering the pipeline in a function. In this way,
the overall operation can use the function that runs the whole process in a
pipeline; or if you want only the filtering part and a different way of getting the
input data, the filter is also available. This sort of thinking in terms of division
of labor and modularity can greatly reduce tweaking and redevelopment time
over the lifetime of scripts.
Use parameterized functions and filters when you must supply control values
for the behavior of the function or filter other than the input data. When
required, typed parameters or default values can be specified. Use of these
technologies and techniques can leverage the abilities of Windows PowerShell
and help you focus on the automation requirements of your scripts.
6-30
6-31
Tools
Most of the tools listed in this module are Windows PowerShell language
constructs that are used for flow control. A notable exception is the ForEach-Object
cmdlet. These constructs are included here for quick reference.
Tool
Use for
Where to find it
ForEach-Object cmdlet
Windows PowerShell
foreach construct
Windows PowerShell
for construct
General looping
Windows PowerShell
while construct
Windows PowerShell
Windows PowerShell
break construct
Windows PowerShell
continue construct
Windows PowerShell
throw construct
Windows PowerShell
return construct
Windows PowerShell
Windows PowerShell
switch construct
Windows PowerShell
function construct
Windows PowerShell
Tool
Use for
Where to find it
Windows PowerShell
6-32
7-1
Module 7
Working with Files, the Registry, and Certificate
Stores
Contents:
Lesson 1: Using Data Stores
7-3
7-10
7-15
7-20
7-23
7-30
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.
7-2
Lesson 1
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-3
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?
7-4
Key Points
Get-PSDrive shows the list of current Windows PowerShell drives.
New-PSDrive creates another Windows PowerShell drive using an existing
provider.
Remove-PSDrive can be used to delete a Windows PowerShell drive.
PSDrives are different from Windows volumes (drives). Creating a new PSDrive
does not create an underlying storage volume in Windows operating systems.
Removing a PSDrive does not delete any underlying storage volumes.
Question: When would you need to delete a Windows PowerShell drive?
7-5
Key Points
Windows PowerShell comes with built-in providers that enable generic access to
several kinds of data stores using generic cmdlets.
You can extend the set of providers to allow access to other types of data stores by
obtaining third-party providers or developing your own.
Question: What are some similarities between file systems, the registry, and
certificate stores?
Question: Can you think of other information stores in Windows operating
systems that also have similarities to these?
7-6
7-7
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?
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, PopLocation, Push-Location, and Set-Location are used to manage the current location.
The default aliases for these cmdlets are:
Pop-Location: popd
Push-Location: pushd
Question: Can you think of a situation in which you might use Push-Location and
Pop-Location?
7-8
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
Question: How would you read the contents of a file into a variable?
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.
7-10
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:
Additional Reading:
For more information on accessing the registry, see Navigating Windows
PowerShell.
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 NewRegistryKey to accomplish this task, or would you simply use the New-Item cmdlet
at a registry location explicitly?
7-12
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.
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?
7-14
7-15
Lesson 3
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?
7-16
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"?
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?
7-18
7-19
Question: Can you think of an application for the switch Regex option?
Lesson 4
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.
7-20
Key Points
The Get-EventLog cmdlet provides access to the event logs:
7-21
7-22
Lesson 5
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-23
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?
7-24
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?
Key Points
You can use the Export-Clixml cmdlet to export objects in an XML schema that is
specific to Windows PowerShell.
The CLiXML format is a command-line interface (CLI) XML schema that is used by
Windows PowerShell to include member type information and data type
information about the properties of the exported objects.
Question: Does the CLiXML format have any advantages over CSV format for
exporting and importing objects in Windows PowerShell?
Question: What are the tradeoffs of using each format?
7-26
7-27
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 ExportClixml?
Key Points
Get-Content brings in the data that was written with Out-File.
Import-CSV brings in the data that was written with Export-CSV.
Import-Clixml reads files that were written with Export-Clixml.
Question: Which import mechanism is best suited to your administration tasks?
7-28
7-29
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?
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.
7-30
7-31
2.
3.
4.
Write a script or command that displays the full path and name of all files in
the folder having the file name extension "txt". For files that contain the word
"PowerShell," also display the line number where the word "PowerShell" can be
found within that file.
Results: After this exercise, you should have located files of a specified file type, or files
having a specified name. You should also have located all files containing a specified
trademarked term.
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.
2.
Create a new setting called TrustPolicy and set it to have a decimal value of 2.
Results: After this exercise, you should have modified the WSH registry settings so that
only scripts that are digitally signed will be executed, regardless of the Software
Restriction Policies settings.
7-32
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.
2.
Use Windows PowerShell to produce a report that shows the location of all
files that have a "bmp" file name extension.
The report should be in CSV format and should contain two columns that
show the directory path and file name of each file.
Use Windows PowerShell to produce a report that shows the location and size
of all files with a file size greater than 10 MB.
The report should exclude files with the file name extension "dll."
The report should be in CSV format, and contain three columns that show the
directory path, file name, and size in bytes of each file.
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.
2.
Retrieve and display the security event log events having an event ID of 4634,
4672, or 4624.
Using the command created for Task 1, create a CSV file containing the event
ID, entry type, and time generated properties for each audit event.
7-34
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.
2.
3.
Create an XML file that contains a snapshot of the services that are currently
installed on the computer.
Compare the snapshot created in Task 1 to the services that are currently
installed on the computer, and display any differences.
Lab Review
7-36
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.
3.
Which cmdlet would you use to find the Windows PowerShell drives that are
currently available?
4.
5.
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?
Troubleshooting tip
Use the Get-Content cmdlet to obtain the contents of a file or files for
processing. Use pipelines, flow control, and string manipulation as
appropriate to work with the contents. Use the [XML] accelerator to access
configuration files and data files that are written in XML format.
Use the iterative capabilities of the switch construct along with the pipeline or
file processing, and regular expression or wildcard matching capabilities to
reduce the amount of code that is required to process files and other content.
Use filters and functions to process data. Filters and functions can be used to
make scripting and interactive automation more modular.
7-38
7-39
Use the Get-EventLog cmdlet to access the event logs. The Newest parameter
of Get-EventLog can be used instead of relying on Select-Object with the First
parameter. The resultant events can be filtered for matches of specific criteria
by using pipelines with cmdlets such as Where-Object or Group-Object.
The HKCU and HKLM PSDrives use the Registry PSProvider to allow access to
the Windows registry. Use Get-ItemProperty to access registry values. Other
*-ItemProperty cmdlets can also be used. The Set-Location and Get-ChildItem
cmdlets can be used for navigating the registry hierarchies.
Use the Export-* and Import-* cmdlets to save and restore objects in persistent
storage. Then use custom code, including cmdlets and constructs such as
switch, foreach, ForEach-Object, and Where-Object to process this data as
necessary. Use CLiXML format for such export and import processing
whenever possible so that the greatest degree of type detail is maintained on
the objects that are imported.
Tools
Tool
Use for
Where to find it
Set-Location
Windows PowerShell
Get-ChildItem
Windows PowerShell
Select-String
Windows PowerShell
Compare-Object
Windows PowerShell
7-40
8-1
Module 8
Managing the Windows Operating System
Using Windows PowerShell and WMI
Contents:
Lesson 1: Introduction to WMI and WMI Objects
Lesson 2: Managing Disks and Disk Volumes Using Windows PowerShell
with WMI
8-3
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
8-22
8-29
Managing the Windows Operating System Using Windows PowerShell and WMI
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.
8-2
Lesson 1
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-3
Managing the Windows Operating System Using Windows PowerShell and WMI
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 information on how to use WMI, see WMI and Windows PowerShell:
Mastering PowerShell in your Lunch Break -- Day 5: Using WMI
8-4
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:
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.
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?
Managing the Windows Operating System Using Windows PowerShell and WMI
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?
8-6
Key Points
Get-WMIObject is the Windows PowerShell cmdlet that you use to integrate
with WMI.
The syntax for the Get-WMIObject cmdlet (not the List form) is as follows:
Get-WMIObject [-class] <string>
[[-property] <string[]>]
[-namespace <string>]
[-computername <string>[]>]
[-filter <string>]
[-credential <PSCredential>]
[<CommonParameters>]
Or as follows:
Get-WMIObject -query <string>
[-namespace <string>]
[-computername <string>[]>]
[-credential <PSCredential>]
[<CommonParameters>]
8-7
Managing the Windows Operating System Using Windows PowerShell and WMI
Managing the Windows Operating System Using Windows PowerShell and WMI
Windows PowerShell provides several type accelerators for use with WMI. The two
most important of these type accelerators are:
[WMI]
[WMICLASS]
The [WMI] accelerator can be used to query an instance of a particular WMI object.
This creates a reference to this object in Windows PowerShell.
Question: Where can you find more information about WMI classes?
Additional Reading:
For basic information on WMI and CIM, see WMI and CIM Concepts and
Terminology
For more information about the Distributed Management Task Force, Inc., see
their Web site.
8-8
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.
Managing the Windows Operating System Using Windows PowerShell and WMI
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?
8-10
8-11
Lesson 2
Managing the Windows Operating System Using Windows PowerShell and WMI
Managing the Windows Operating System Using Windows PowerShell and WMI
Key Points
WMI has several classes for working with disks, volumes, and disk I/O. Two key
classes include:
These classes can be used to manage (disk) storage volumes. You can use
Win32_DiskDrive to obtain information about physical disks and use
Win32_Volume to get information about individual volumes (partitions).
Question: How would you find the definition of Win32_DiskDrive?
8-12
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-13
Managing the Windows Operating System Using Windows PowerShell and WMI
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 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?
8-14
8-15
Lesson 3
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.
Managing the Windows Operating System Using Windows PowerShell and WMI
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.
Question: Can you think of possible uses of shadow copies?
Additional Reading:
For a description of how VSS works, see How Volume Shadow Copy Service
Works.
8-16
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
8-17
Managing the Windows Operating System Using Windows PowerShell and WMI
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:
8-18
8-19
Lesson 4
This lesson explains how to manage shared folders using WMI. With WMI you can
list existing shares and create new shared folders.
Managing the Windows Operating System Using Windows PowerShell and WMI
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: When would you use WMI to manage file shares?
Question: Which properties and methods does WMI implement for shared
folders?
8-20
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-21
Managing the Windows Operating System Using Windows PowerShell and WMI
Managing the Windows Operating System Using Windows PowerShell and WMI
Lesson 5
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.
8-22
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.
Question: Do you use Terminal Services currently?
Additional Reading:
For more information on Terminal Services features, see What's New in Terminal
Services for Windows Server 2008
Managing the Windows Operating System Using Windows PowerShell and WMI
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: How do you manage your terminal server farm currently?
Question: Do you see any advantage of using the new Terminal Services WMI
provider?
8-24
Key Points
You can use the Get-WMIObject cmdlet to get a list of WMI classes (use the List
parameter).
Question: Are all these WMI classes useful to an administrator?
8-25
Managing the Windows Operating System Using Windows PowerShell and WMI
Managing the Windows Operating System Using Windows PowerShell and WMI
Key Points:
There are over 40 classes, divided into 5 main sets. Each set is described separately
in MSDN.
Remember that when you retrieve Terminal Services WMI classes, you must
specify the namespace.
Question: How would you find out the individual properties and methods on
each class?
Additional Reading:
For more information about Terminal Services, see Terminal Services WMI
Provider Reference.
8-26
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?
Managing the Windows Operating System Using Windows PowerShell and WMI
Managing the Windows Operating System Using Windows PowerShell and WMI
Additional Reading:
For information on the Terminal Services WMI provider and related classes,
see Terminal Services WMI Provider Reference.
8-28
8-29
Lesson 6
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.
Managing the Windows Operating System Using Windows PowerShell and WMI
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.
8-30
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?
Managing the Windows Operating System Using Windows PowerShell and WMI
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:
8-32
8-33
Managing the Windows Operating System Using Windows PowerShell and WMI
Managing the Windows Operating System Using Windows PowerShell and WMI
Exercise Overview
In this exercise, you will use WMI classes in Windows PowerShell.
The main tasks for this exercise are as follows:
1.
2.
Retrieve the operating system and service pack version information from a
computer.
3.
4.
Display only those properties that contain the operating system build number
and the major version number of the latest installed service pack.
Complete this task using a technique that can be used either for the local
computer or for remote computers.
Create a list of installed services that includes the service name, the user
account that the service uses to log on, and the start mode that the service is
configured to use.
8-34
8-35
Retrieve all instances of the Win32_Share class that have a Name property
containing "FileShare".
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.
2.
3.
Managing the Windows Operating System Using Windows PowerShell and WMI
Managing the Windows Operating System Using Windows PowerShell and WMI
Use the Create() method of the Win32_Share class to create a new shared
folder named Docs for the C:\SharedDocuments folder.
Exercise Overview
In this exercise, you will manage disk volumes in Windows PowerShell.
The main tasks for this exercise are as follows:
1.
2.
Create a report that uses the Win32_Volume class to display the drive letter,
total space, and free space for local hard disks only.
8-36
8-37
Create a report that shows all attached volumes. The report should include the
volume name (drive letter) and its drive type number.
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.
Use WMI to obtain the Win32_Volume instance that represents the E drive.
Note that the backslash (\) character is a special character in WMI. If you
specify a filter, you must type two backslashes. For example, instead of "E:\,"
you would type "E:\\."
Managing the Windows Operating System Using Windows PowerShell and WMI
Managing the Windows Operating System Using Windows PowerShell and WMI
Results: After this exercise, you should have defragmented the E drive on your virtual
machine.
Exercise Overview
In this exercise, students will manage IIS 7.0 properties by using WMI.
The main tasks for this exercise are as follows:
1.
2.
3.
4.
Management Service
8-38
Use the function to retrieve the status of the default Web site.
8-39
Managing the Windows Operating System Using Windows PowerShell and WMI
Managing the Windows Operating System Using Windows PowerShell and WMI
Lab Review
8-40
8-41
Review Questions
1.
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.
Managing the Windows Operating System Using Windows PowerShell and WMI
Managing the Windows Operating System Using Windows PowerShell and WMI
Troubleshooting tip
2.
Consider writing some simple wrapper functions to speed up your use of WMI
classes.
8-42
8-43
Learn both the WMI and .NET management approaches for IIS 7.0
administration.
Use the WMI management approach for IIS 7.0 when you need to quickly
modify specific sections or elements.
Tools
Tool
Use for
Where to find it
WMI Explorer
Searching WMI
Locating information
on WMI classes that
you can access with
Windows PowerShell
Appcmd.exe
Text-oriented
management of IIS 7.0
WMI
Root\WebAdministration
namespace
Windows PowerShell
Windows PowerShell
samples under Community
Content
Managing the Windows Operating System Using Windows PowerShell and WMI
Managing the Windows Operating System Using Windows PowerShell and WMI
8-44
9-1
Module 9
Administering Microsoft Active Directory
with Windows PowerShell
Contents:
Lesson 1: Administering Domains and Forests Using .NET Objects
9-3
9-9
9-17
9-23
9-27
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.
9-2
9-3
Lesson 1
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.
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?
9-4
9-5
System.DirectoryServices.ActiveDirectory.Forest Class
Key Points:
.NET Framework includes a class for working with certain aspects of an
Active Directory forest. The class is called
System.DirectoryServices.ActiveDirectory.Forest. You can invoke the
GetCurrentForest method on that class to return a reference object for the current
forest. Several additional methods are available to perform administrative tasks at
the forest level.
Forest operations include creating and deleting trust relationships, finding global
catalogs (GCs), getting all existing trust relationships, and managing security
identifier (SID) filtering.
Question: Which operations can be performed with a reference to the current
Active Directory forest?
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:
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?
9-6
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.
Question: How would you query for all current global catalog servers in an
Active Directory forest?
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?
9-8
9-9
Lesson 2
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.
Key Points
The ADSI is a set of COM interfaces that can be used to access Active Directory. It
can also access Windows NT Security Account Manager (SAM) style domains
(local per workstation or server) and other non-Microsoft directories.
Availability of ADSI in Windows PowerShell facilitates the querying, searching,
creation, deletion, and modification of objects in Active Directory.
Question: How would you create a reference to an existing object in your
Active Directory?
Additional Reading:
For more information on the LDAP URL Format, see RFC 2255.
9-10
Question: How would you write an LDAP URL to refer to an OU in your own
Active Directory environment?
9-11
9-12
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?
Additional Reading:
For an overview of the Active Directory schema, see Active Directory Schema
on the MSDN.
9-14
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
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.
Question: How would you modify the same property of several users at once?
9-16
9-17
Lesson 3
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.
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?
9-18
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?
Question: How would you write a Windows PowerShell function to return all of
the people who work for a particular manager?
9-20
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?
Question: How would you enumerate all the groups that a user is a member of?
9-22
9-23
Lesson 4
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.
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.
9-24
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.
Question: What is the advantage of using the .NET Web.Administration interface
as opposed to using the WMI WebAdministration namespace?
Additional Reading:
For more information on Web server management, see .NET Framework Class
Library: ServerManager Class.
9-26
9-27
Exercise Overview
In this exercise, students will manage Active Directory domain and forest
properties.
The main tasks for this exercise are as follows:
1.
2.
Display the following settings from the password policy for the domain:
Results: After this exercise, you should have displayed the domain password policies
for your domain.
9-28
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.
2.
3.
Write a script that imports the CSV file and creates user accounts.
$dom = [ADSI]"LDAP://dc=woodgrovebank,dc=com"
$ou.SetInfo()
Double-check to be sure that Windows Notepad does not add a "txt" filename
extension.
FullName,LogonName,Branch
Syed Abbas,Syed,Seattle
f Task 3: Write a script that imports the CSV file and creates
user accounts
For each line in the file, excluding the first row, create a new user account.
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.
9-30
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.
2.
Run a command that retrieves the user account for Kristian Gotsch in the
Executives OU. Store the account in the variable $mgr.
Dot source the GetUser.ps1 and SetUser.ps1 scripts into the shell.
Results: After this exercise, you should have updated two user accounts to have a new
manager attribute.
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.
f Task 1: Write a Windows PowerShell script that creates a new Web site
9-32
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.
Lab Review
9-34
9-35
Review Questions
1.
Which technique is used for finding all global catalog servers in a forest?
2.
3.
Troubleshooting tip
Issue
Troubleshooting tip
Define Active Directory access functions to meet your common needs for
Active Directory management.
Use pipelines with Active Directory access functions instead of making each
function handle all aspects of a problem.
Learn both the WMI and .NET management approaches for administering IIS
7.0.
Use the .NET Web.Administration interface for IIS 7.0 management whenever
possible.
9-36
Tools
Tool
Use for
Where to find it
[ADSI]
Windows
PowerShell
DirectorySearcher class
Windows
PowerShell
.NET
Microsoft.Web.Administratio
n assembly
Structured management of
IIS 7.0
Windows
PowerShell
9-37
10-1
Module 10
Administering Group Policy in Windows
PowerShell Using COM
Contents:
Lesson 1: Managing GPOs Using the GPMC COM Interface
10-3
10-11
10-15
10-18
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.
10-2
10-3
Lesson 1
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.
Key Points
You can use Windows PowerShell to refer to COM objects:
COM objects can be generated using the New-Object cmdlet with the
ComObject parameter.
Methods and properties of COM objects are accessed as if they were .NET
objects in Windows PowerShell.
To make a reference to a COM object, use the New-Object cmdlet and include the
ComObject parameter in addition to the COM class name.
Question: How would you create a reference object to automate management of
Internet Explorer via COM?
10-4
10-5
Key Points
The GPMC is the hub for Group Policy management. However, it does not actually
manage the Group Policy settings within GPOs.
The GPMC also provides a COM interface to enable you to programmatically
access various GPO functions and features.
Question: Have you used the GPMC interface before?
Additional Reading:
For more information about GPMC, please see:
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:
Question: Where would you look for more information on using the GPMC
interface with Windows PowerShell?
10-6
Additional Reading:
For additional information about the GPMC COM API, please see GPMC Object
Model.
10-7
Additional Reading:
For additional information about creating GPOs using
Windows PowerShell, please see CreateGPO Method of the IGPMDomain Interface
10-8
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?
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:
Use the CopyTo method on the source GPO, specifying the domain and the
display name of the new GPO.
10-10
10-11
Lesson 2
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.
Key Points
The GPMC COM interface implements a searching mechanism that works as
follows:
Add any required criteria to these search criteria (for example, to search for a
specific GPO) using constants to describe the specific criterion.
Note: Starter GPOs are not enabled by default. You enable them by using the
GPMC GUI.
10-12
10-13
Backing Up GPOs
Key Points
On the GPM COM interface, you can back up GPOs one at a time by using the
Backup method of a GPO object. If you want to back up multiple GPOs, you must
call Backup() multiple times.
To back up a GPO, you must first get the GPO object that relates to the GPO that
you want to back up. Then use the Backup method of the GPO to perform backup
and check results.
Question: How often should you perform GPO backups?
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?
10-14
Lesson 3
This lesson looks at reporting with GPOs, including RSOP. This ability helps
administrators to develop reports on GPOS in their environment,
10-15
Key Points
Resultant Set of Policy (RSoP) is what happens when policy is applied, including
dealing with:
Local/Site/Domain/OUs
Multiple policies
Loopback
10-16
10-17
Key Points
The GPMC interface provides some good reporting. You can report to XML or to
HTML. You can use these reporting interfaces to create reports as needed. For
example:
Foreach ($gpo in $gpos) {
$result=$gpo.GenerateReport($k.ReportHTML)
$x=$result.result
}
# Create output of last one
$x | set-content outgpo.html
# View it
& .\outgpo.html
Exercise Overview
In this exercise, you will use COM objects in Windows PowerShell.
The main tasks for this exercise are as follows:
1.
2.
Retrieve the GPO that has the display name GPO1, and store it in a variable.
10-18
10-19
f Task 2: Retrieve the GPO that has the display name GPO1, and store it
in a variable
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".
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 GPO1 to a new GPO named GPO3. Use the CopyTo() method of the
$gpo object, and use the $domain object as a target.
Results: After this exercise, you should have copied GPO1 to GPO3.
Exercise Overview
In this exercise, students will back up and restore GPOs.
The main tasks for this exercise are as follows:
1.
2.
3.
Use the Backup() method of the $gpo object to back up GPO1 to a file named
GPO1Backup.
Use the GPMC to delete the GPO1 GPO, which is linked to the Tellers OU.
10-20
10-21
Use the Where-Object cmdlet to filter out all GPOs that do not have a
GPODisplayName property of GPO1. Store the remaining GPO in a variable
named $backup.
Use the RestoreGPO() method of the domain to restore the $backup object.
Results: After this exercise, you should have backed up, deleted, and restored a GPO.
Exercise Overview
In this exercise, you will generate Group Policy change reports.
The main tasks for this exercise are as follows:
1.
Lab Review
10-22
10-23
Review Questions
1.
What would you use Windows PowerShell for in terms of managing GPOs?
2.
3.
Troubleshooting tip
Build some simple functions (get-GPO, etc) and place them in your
$profile file.
Tools
Tool
Use for
Where to find it
GPMC
Administrative Tools
GPMC API
Windows PowerShell
10-24
10-25
Course Evaluation
Your evaluation of this course will help Microsoft understand the quality of your
learning experience.
Please work with your training provider to access the course evaluation form.
Microsoft will keep your answers to this survey private and confidential and will
use your responses to improve your future learning experience. Your open and
honest feedback is valuable and appreciated.