Вы находитесь на странице: 1из 130

O F F I C I A L M I C R O S O F T L E A R N I N G P R O D U C T

10961B
Automating Administration
with Windows PowerShell®
ii 10961B: Automating Administration with Windows PowerShell®

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.

© 2013 Microsoft Corporation. All rights reserved.

Microsoft and the trademarks listed at


http://www.microsoft.com/about/legal/en/us/IntellectualProperty/Trademarks/EN-US.aspx are trademarks of
the Microsoft group of companies. All other trademarks are property of their respective owners

Product Number: 10961B

Part Number: X18-84549

Released: September 2013


MICROSOFT LICENSE TERMS
MICROSOFT INSTRUCTOR-LED COURSEWARE

These license terms are an agreement between Microsoft Corporation (or based on where you live, one of its
affiliates) and you. Please read them. They apply to your use of the content accompanying this agreement which
includes the media on which you received it, if any. These license terms also apply to Trainer Content and any
updates and supplements for the Licensed Content unless other terms accompany those items. If so, those terms
apply.

BY ACCESSING, DOWNLOADING OR USING THE LICENSED CONTENT, YOU ACCEPT THESE TERMS.
IF YOU DO NOT ACCEPT THEM, DO NOT ACCESS, DOWNLOAD OR USE THE LICENSED CONTENT.

If you comply with these license terms, you have the rights below for each license you acquire.

1. DEFINITIONS.

a. “Authorized Learning Center” means a Microsoft IT Academy Program Member, Microsoft Learning
Competency Member, or such other entity as Microsoft may designate from time to time.

b. “Authorized Training Session” means the instructor-led training class using Microsoft Instructor-Led
Courseware conducted by a Trainer at or through an Authorized Learning Center.

c. “Classroom Device” means one (1) dedicated, secure computer that an Authorized Learning Center owns
or controls that is located at an Authorized Learning Center’s training facilities that meets or exceeds the
hardware level specified for the particular Microsoft Instructor-Led Courseware.

d. “End User” means an individual who is (i) duly enrolled in and attending an Authorized Training Session
or Private Training Session, (ii) an employee of a MPN Member, or (iii) a Microsoft full-time employee.

e. “Licensed Content” means the content accompanying this agreement which may include the Microsoft
Instructor-Led Courseware or Trainer Content.

f. “Microsoft Certified Trainer” or “MCT” means an individual who is (i) engaged to teach a training session
to End Users on behalf of an Authorized Learning Center or MPN Member, and (ii) currently certified as a
Microsoft Certified Trainer under the Microsoft Certification Program.

g. “Microsoft Instructor-Led Courseware” means the Microsoft-branded instructor-led training course that
educates IT professionals and developers on Microsoft technologies. A Microsoft Instructor-Led
Courseware title may be branded as MOC, Microsoft Dynamics or Microsoft Business Group courseware.

h. “Microsoft IT Academy Program Member” means an active member of the Microsoft IT Academy
Program.

i. “Microsoft Learning Competency Member” means an active member of the Microsoft Partner Network
program in good standing that currently holds the Learning Competency status.

j. “MOC” means the “Official Microsoft Learning Product” instructor-led courseware known as Microsoft
Official Course that educates IT professionals and developers on Microsoft technologies.

k. “MPN Member” means an active silver or gold-level Microsoft Partner Network program member in good
standing.
l. “Personal Device” means one (1) personal computer, device, workstation or other digital electronic device
that you personally own or control that meets or exceeds the hardware level specified for the particular
Microsoft Instructor-Led Courseware.

m. “Private Training Session” means the instructor-led training classes provided by MPN Members for
corporate customers to teach a predefined learning objective using Microsoft Instructor-Led Courseware.
These classes are not advertised or promoted to the general public and class attendance is restricted to
individuals employed by or contracted by the corporate customer.

n. “Trainer” means (i) an academically accredited educator engaged by a Microsoft IT Academy Program
Member to teach an Authorized Training Session, and/or (ii) a MCT.

o. “Trainer Content” means the trainer version of the Microsoft Instructor-Led Courseware and additional
supplemental content designated solely for Trainers’ use to teach a training session using the Microsoft
Instructor-Led Courseware. Trainer Content may include Microsoft PowerPoint presentations, trainer
preparation guide, train the trainer materials, Microsoft One Note packs, classroom setup guide and Pre-
release course feedback form. To clarify, Trainer Content does not include any software, virtual hard
disks or virtual machines.

2. USE RIGHTS. The Licensed Content is licensed not sold. The Licensed Content is licensed on a one copy
per user basis, such that you must acquire a license for each individual that accesses or uses the Licensed
Content.

2.1 Below are five separate sets of use rights. Only one set of rights apply to you.

a. If you are a Microsoft IT Academy Program Member:


i. Each license acquired on behalf of yourself may only be used to review one (1) copy of the Microsoft
Instructor-Led Courseware in the form provided to you. If the Microsoft Instructor-Led Courseware is
in digital format, you may install one (1) copy on up to three (3) Personal Devices. You may not
install the Microsoft Instructor-Led Courseware on a device you do not own or control.
ii. For each license you acquire on behalf of an End User or Trainer, you may either:
1. distribute one (1) hard copy version of the Microsoft Instructor-Led Courseware to one (1) End
User who is enrolled in the Authorized Training Session, and only immediately prior to the
commencement of the Authorized Training Session that is the subject matter of the Microsoft
Instructor-Led Courseware being provided, or
2. provide one (1) End User with the unique redemption code and instructions on how they can
access one (1) digital version of the Microsoft Instructor-Led Courseware, or
3. provide one (1) Trainer with the unique redemption code and instructions on how they can
access one (1) Trainer Content,
provided you comply with the following:
iii. you will only provide access to the Licensed Content to those individuals who have acquired a valid
license to the Licensed Content,
iv. you will ensure each End User attending an Authorized Training Session has their own valid licensed
copy of the Microsoft Instructor-Led Courseware that is the subject of the Authorized Training
Session,
v. you will ensure that each End User provided with the hard-copy version of the Microsoft Instructor-
Led Courseware will be presented with a copy of this agreement and each End User will agree that
their use of the Microsoft Instructor-Led Courseware will be subject to the terms in this agreement
prior to providing them with the Microsoft Instructor-Led Courseware. Each individual will be required
to denote their acceptance of this agreement in a manner that is enforceable under local law prior to
their accessing the Microsoft Instructor-Led Courseware,
vi. you will ensure that each Trainer teaching an Authorized Training Session has their own valid
licensed copy of the Trainer Content that is the subject of the Authorized Training Session,
vii. you will only use qualified Trainers who have in-depth knowledge of and experience with the
Microsoft technology that is the subject of the Microsoft Instructor-Led Courseware being taught for
all your Authorized Training Sessions,
viii. you will only deliver a maximum of 15 hours of training per week for each Authorized Training
Session that uses a MOC title, and
ix. you acknowledge that Trainers that are not MCTs will not have access to all of the trainer resources
for the Microsoft Instructor-Led Courseware.

b. If you are a Microsoft Learning Competency Member:


i. Each license acquired on behalf of yourself may only be used to review one (1) copy of the Microsoft
Instructor-Led Courseware in the form provided to you. If the Microsoft Instructor-Led Courseware is
in digital format, you may install one (1) copy on up to three (3) Personal Devices. You may not
install the Microsoft Instructor-Led Courseware on a device you do not own or control.
ii. For each license you acquire on behalf of an End User or Trainer, you may either:
1. distribute one (1) hard copy version of the Microsoft Instructor-Led Courseware to one (1) End
User attending the Authorized Training Session and only immediately prior to the
commencement of the Authorized Training Session that is the subject matter of the Microsoft
Instructor-Led Courseware provided, or
2. provide one (1) End User attending the Authorized Training Session with the unique redemption
code and instructions on how they can access one (1) digital version of the Microsoft Instructor-
Led Courseware, or
3. you will provide one (1) Trainer with the unique redemption code and instructions on how they
can access one (1) Trainer Content,
provided you comply with the following:
iii. you will only provide access to the Licensed Content to those individuals who have acquired a valid
license to the Licensed Content,
iv. you will ensure that each End User attending an Authorized Training Session has their own valid
licensed copy of the Microsoft Instructor-Led Courseware that is the subject of the Authorized
Training Session,
v. you will ensure that each End User provided with a hard-copy version of the Microsoft Instructor-Led
Courseware will be presented with a copy of this agreement and each End User will agree that their
use of the Microsoft Instructor-Led Courseware will be subject to the terms in this agreement prior to
providing them with the Microsoft Instructor-Led Courseware. Each individual will be required to
denote their acceptance of this agreement in a manner that is enforceable under local law prior to
their accessing the Microsoft Instructor-Led Courseware,
vi. you will ensure that each Trainer teaching an Authorized Training Session has their own valid
licensed copy of the Trainer Content that is the subject of the Authorized Training Session,
vii. you will only use qualified Trainers who hold the applicable Microsoft Certification credential that is
the subject of the Microsoft Instructor-Led Courseware being taught for your Authorized Training
Sessions,
viii. you will only use qualified MCTs who also hold the applicable Microsoft Certification credential that is
the subject of the MOC title being taught for all your Authorized Training Sessions using MOC,
ix. you will only provide access to the Microsoft Instructor-Led Courseware to End Users, and
x. you will only provide access to the Trainer Content to Trainers.
c. If you are a MPN Member:
i. Each license acquired on behalf of yourself may only be used to review one (1) copy of the Microsoft
Instructor-Led Courseware in the form provided to you. If the Microsoft Instructor-Led Courseware is
in digital format, you may install one (1) copy on up to three (3) Personal Devices. You may not
install the Microsoft Instructor-Led Courseware on a device you do not own or control.
ii. For each license you acquire on behalf of an End User or Trainer, you may either:
1. distribute one (1) hard copy version of the Microsoft Instructor-Led Courseware to one (1) End
User attending the Private Training Session, and only immediately prior to the commencement
of the Private Training Session that is the subject matter of the Microsoft Instructor-Led
Courseware being provided, or
2. provide one (1) End User who is attending the Private Training Session with the unique
redemption code and instructions on how they can access one (1) digital version of the
Microsoft Instructor-Led Courseware, or
3. you will provide one (1) Trainer who is teaching the Private Training Session with the unique
redemption code and instructions on how they can access one (1) Trainer Content,
provided you comply with the following:
iii. you will only provide access to the Licensed Content to those individuals who have acquired a valid
license to the Licensed Content,
iv. you will ensure that each End User attending an Private Training Session has their own valid licensed
copy of the Microsoft Instructor-Led Courseware that is the subject of the Private Training Session,
v. you will ensure that each End User provided with a hard copy version of the Microsoft Instructor-Led
Courseware will be presented with a copy of this agreement and each End User will agree that their
use of the Microsoft Instructor-Led Courseware will be subject to the terms in this agreement prior to
providing them with the Microsoft Instructor-Led Courseware. Each individual will be required to
denote their acceptance of this agreement in a manner that is enforceable under local law prior to
their accessing the Microsoft Instructor-Led Courseware,
vi. you will ensure that each Trainer teaching an Private Training Session has their own valid licensed
copy of the Trainer Content that is the subject of the Private Training Session,
vii. you will only use qualified Trainers who hold the applicable Microsoft Certification credential that is
the subject of the Microsoft Instructor-Led Courseware being taught for all your Private Training
Sessions,
viii. you will only use qualified MCTs who hold the applicable Microsoft Certification credential that is the
subject of the MOC title being taught for all your Private Training Sessions using MOC,
ix. you will only provide access to the Microsoft Instructor-Led Courseware to End Users, and
x. you will only provide access to the Trainer Content to Trainers.

d. If you are an End User:


For each license you acquire, you may use the Microsoft Instructor-Led Courseware solely for your
personal training use. If the Microsoft Instructor-Led Courseware is in digital format, you may access the
Microsoft Instructor-Led Courseware online using the unique redemption code provided to you by the
training provider and install and use one (1) copy of the Microsoft Instructor-Led Courseware on up to
three (3) Personal Devices. You may also print one (1) copy of the Microsoft Instructor-Led Courseware.
You may not install the Microsoft Instructor-Led Courseware on a device you do not own or control.

e. If you are a Trainer.


i. For each license you acquire, you may install and use one (1) copy of the Trainer Content in the
form provided to you on one (1) Personal Device solely to prepare and deliver an Authorized
Training Session or Private Training Session, and install one (1) additional copy on another Personal
Device as a backup copy, which may be used only to reinstall the Trainer Content. You may not
install or use a copy of the Trainer Content on a device you do not own or control. You may also
print one (1) copy of the Trainer Content solely to prepare for and deliver an Authorized Training
Session or Private Training Session.
ii. You may customize the written portions of the Trainer Content that are logically associated with
instruction of a training session in accordance with the most recent version of the MCT agreement.
If you elect to exercise the foregoing rights, you agree to comply with the following: (i)
customizations may only be used for teaching Authorized Training Sessions and Private Training
Sessions, and (ii) all customizations will comply with this agreement. For clarity, any use of
“customize” refers only to changing the order of slides and content, and/or not using all the slides or
content, it does not mean changing or modifying any slide or content.

2.2 Separation of Components. The Licensed Content is licensed as a single unit and you may not
separate their components and install them on different devices.

2.3 Redistribution of Licensed Content. Except as expressly provided in the use rights above, you may
not distribute any Licensed Content or any portion thereof (including any permitted modifications) to any
third parties without the express written permission of Microsoft.

2.4 Third Party Programs and Services. The Licensed Content may contain third party programs or
services. These license terms will apply to your use of those third party programs or services, unless other
terms accompany those programs and services.

2.5 Additional Terms. Some Licensed Content may contain components with additional terms,
conditions, and licenses regarding its use. Any non-conflicting terms in those conditions and licenses also
apply to your use of that respective component and supplements the terms described in this agreement.

3. LICENSED CONTENT BASED ON PRE-RELEASE TECHNOLOGY. If the Licensed Content’s subject


matter is based on a pre-release version of Microsoft technology (“Pre-release”), then in addition to the
other provisions in this agreement, these terms also apply:

a. Pre-Release Licensed Content. This Licensed Content subject matter is on the Pre-release version of
the Microsoft technology. The technology may not work the way a final version of the technology will
and we may change the technology for the final version. We also may not release a final version.
Licensed Content based on the final version of the technology may not contain the same information as
the Licensed Content based on the Pre-release version. Microsoft is under no obligation to provide you
with any further content, including any Licensed Content based on the final version of the technology.

b. Feedback. If you agree to give feedback about the Licensed Content to Microsoft, either directly or
through its third party designee, 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, Microsoft product, or service that includes the feedback. You
will not give feedback that is subject to a license that requires Microsoft to license its software,
technologies, or products to third parties because we include your feedback in them. These rights
survive this agreement.

c. Pre-release Term. If you are an Microsoft IT Academy Program Member, Microsoft Learning
Competency Member, MPN Member or Trainer, you will cease using all copies of the Licensed Content on
the Pre-release technology upon (i) the date which Microsoft informs you is the end date for using the
Licensed Content on the Pre-release technology, or (ii) sixty (60) days after the commercial release of the
technology that is the subject of the Licensed Content, whichever is earliest (“Pre-release term”).
Upon expiration or termination of the Pre-release term, you will irretrievably delete and destroy all copies
of the Licensed Content in your possession or under your control.
4. 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
allows you to use it in certain ways. Except as expressly permitted in this agreement, you may not:
 access or allow any individual to access the Licensed Content if they have not acquired a valid license
for the Licensed Content,
 alter, remove or obscure any copyright or other protective notices (including watermarks), branding
or identifications contained in the Licensed Content,
 modify or create a derivative work of any Licensed Content,
 publicly display, or make the Licensed Content available for others to access or use,
 copy, print, install, sell, publish, transmit, lend, adapt, reuse, link to or post, make available or
distribute the Licensed Content to any third party,
 work around any technical limitations in the Licensed Content, or
 reverse engineer, decompile, remove or otherwise thwart any protections or disassemble the
Licensed Content except and only to the extent that applicable law expressly permits, despite this
limitation.

5. RESERVATION OF RIGHTS AND OWNERSHIP. Microsoft reserves all rights not expressly granted to
you in this agreement. The Licensed Content is protected by copyright and other intellectual property laws
and treaties. Microsoft or its suppliers own the title, copyright, and other intellectual property rights in the
Licensed Content.

6. 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.

7. SUPPORT SERVICES. Because the Licensed Content is “as is”, we may not provide support services for it.

8. TERMINATION. Without prejudice to any other rights, Microsoft may terminate this agreement if you fail
to comply with the terms and conditions of this agreement. Upon termination of this agreement for any
reason, you will immediately stop all use of and delete and destroy all copies of the Licensed Content in
your possession or under your control.

9. LINKS TO THIRD PARTY SITES. You may link to third party sites through the use of the Licensed
Content. The third party sites are not under the control of Microsoft, and Microsoft is not responsible for
the contents of any third party sites, any links contained in third party sites, or any changes or updates to
third party sites. Microsoft is not responsible for webcasting or any other form of transmission received
from any third party sites. Microsoft is providing these links to third party sites to you only as a
convenience, and the inclusion of any link does not imply an endorsement by Microsoft of the third party
site.

10. ENTIRE AGREEMENT. This agreement, and any additional terms for the Trainer Content, updates and
supplements are the entire agreement for the Licensed Content, updates and supplements.

11. APPLICABLE LAW.


a. United States. If you acquired the Licensed Content in the United States, Washington state law governs
the interpretation of this agreement and applies to claims for breach of it, regardless of conflict of laws
principles. The laws of the state where you live govern all other claims, including claims under state
consumer protection laws, unfair competition laws, and in tort.
b. Outside the United States. If you acquired the Licensed Content in any other country, the laws of that
country apply.

12. 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.

13. DISCLAIMER OF WARRANTY. THE LICENSED CONTENT IS LICENSED "AS-IS" AND "AS
AVAILABLE." YOU BEAR THE RISK OF USING IT. MICROSOFT AND ITS RESPECTIVE
AFFILIATES 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 AND
ITS RESPECTIVE AFFILIATES EXCLUDES ANY IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.

14. LIMITATION ON AND EXCLUSION OF REMEDIES AND DAMAGES. YOU CAN RECOVER FROM
MICROSOFT, ITS RESPECTIVE AFFILIATES AND ITS SUPPLIERS ONLY DIRECT DAMAGES UP
TO US$5.00. YOU CANNOT RECOVER ANY OTHER DAMAGES, INCLUDING CONSEQUENTIAL,
LOST PROFITS, SPECIAL, INDIRECT OR INCIDENTAL DAMAGES.

This limitation applies to


o anything related to the Licensed Content, services, content (including code) on third party Internet
sites or third-party programs; and
o claims for breach of contract, breach of warranty, guarantee or condition, strict liability, negligence,
or other tort to the extent permitted by applicable law.

It also applies even if Microsoft knew or should have known about the possibility of the damages. The
above limitation or exclusion may not apply to you because your country may not allow the exclusion or
limitation of incidental, consequential or other damages.

Please note: As this Licensed Content is distributed in Quebec, Canada, some of the clauses in this
agreement are provided below in French.

Remarque : Ce le contenu sous licence étant distribué au Québec, Canada, certaines des clauses
dans ce contrat sont fournies ci-dessous en français.

EXONÉRATION DE GARANTIE. Le contenu sous licence visé par une licence est offert « tel quel ». Toute
utilisation de ce contenu sous licence est à votre seule risque et péril. Microsoft n’accorde aucune autre garantie
expresse. Vous pouvez bénéficier de droits additionnels en vertu du droit local sur la protection dues
consommateurs, que ce contrat ne peut modifier. La ou elles sont permises par le droit locale, les garanties
implicites de qualité marchande, d’adéquation à un usage particulier et d’absence de contrefaçon sont exclues.

LIMITATION DES DOMMAGES-INTÉRÊTS ET EXCLUSION DE RESPONSABILITÉ POUR LES


DOMMAGES. Vous pouvez obtenir de Microsoft et de ses fournisseurs une indemnisation en cas de dommages
directs uniquement à hauteur de 5,00 $ US. Vous ne pouvez prétendre à aucune indemnisation pour les autres
dommages, y compris les dommages spéciaux, indirects ou accessoires et pertes de bénéfices.
Cette limitation concerne:
 tout ce qui est relié au le contenu sous licence, aux services ou au contenu (y compris le code)
figurant sur des sites Internet tiers ou dans des programmes tiers; et.
 les réclamations au titre de violation de contrat ou de garantie, ou au titre de responsabilité
stricte, de négligence ou d’une autre faute dans la limite autorisée par la loi en vigueur.
Elle s’applique également, même si Microsoft connaissait ou devrait connaître l’éventualité d’un tel dommage. Si
votre pays n’autorise pas l’exclusion ou la limitation de responsabilité pour les dommages indirects, accessoires
ou de quelque nature que ce soit, il se peut que la limitation ou l’exclusion ci-dessus ne s’appliquera pas à votre
égard.

EFFET JURIDIQUE. Le présent contrat décrit certains droits juridiques. Vous pourriez avoir d’autres droits
prévus par les lois de votre pays. Le présent contrat ne modifie pas les droits que vous confèrent les lois de votre
pays si celles-ci ne le permettent pas.

Revised September 2012


Getting Started with Windows PowerShell 01-1

Module01
Getting Started with Windows PowerShell
Contents:
Lesson 1: Overview and Background 2 

Lesson 2: Finding and Learning Commands 5 

Lesson 3: Running Commands 8 


Module Review and Takeaways 11 

Lab Review Questions and Answers 11 


01-2 Automating Administration with Windows PowerShell

Lesson 1
Overview and Background
Contents:
Question and Answers 3
Demonstration 3
Getting Started with Windows PowerShell 01-3

Question and Answers


Question: Why might you decide to use the ISE over the console host?

Answer: The ISE supports richer editing capabilities and can display a wider range of fonts. It is also
compatible with double-byte character sets, making it compatible with a wider variety of written
languages. However, the ISE does not provide the same features as the console. For example, the ISE
cannot use the Start-Transcript command.

Demonstration
Demonstration: Configuring the Console

Demonstration Steps
1. Press the Windows key to display the Start screen. Then, type powersh to display the Windows
PowerShell icon. Right-click it, and then select Run as administrator.

2. As soon as Windows PowerShell is running, right-click the icon on the taskbar and select Pin this
program to taskbar.

Ensure that the window title bar says Administrator and that it does not say (x86).
3. Click the control box in the upper-left corner of the console application window, and then select
Properties from the pop-up menu.

4. On the Font tab, select Consolas, and select an appropriate font size. (A font size of between 20 to
28 points is usually appropriate for a display on a projector in front of the class.)

5. On the Layout tab, change the Window Size area’s Width and Height values so that the whole
window fits on the screen.

6. After you do this, set the Screen Buffer area’s Width value to be the same as the Window Size
Width value. Be aware that the horizontal scroll bar is not displayed at the bottom of the window.
Click OK.
7. To start a transcript, run:

Start-Transcript C:\Day1.txt

8. Be aware that the transcript will be active only for this Windows PowerShell window, and only for as
long as this window is open.
Demonstration: Configuring the ISE

Demonstration Steps
1. Right-click the Windows PowerShell taskbar icon and select Run ISE as Administrator.

2. As soon as the ISE is open, close it.

3. In the Windows PowerShell console, type ise and then press Enter.

4. Use the three layout buttons on the ISE toolbar to change the layout from one-above-the-other, side-
by-side, and single-pane views. Finish by switching to single-pane view.

5. Use the blue arrow at the upper-right of the pane to show and hide the Script Pane, toggling
between the script and console panes.

6. Use the rightmost two toolbar buttons in the ISE to show and hide the docked and floating
Command Panes.
01-4 Automating Administration with Windows PowerShell

7. Use the slider in the lower-right corner of the window to adjust the font size in the console and the
Script Panes.

8. On the Tools menu in the ISE, select Options. Click Manage Themes and select a theme, such as
Presentation. Click OK to close the dialog boxes.
Getting Started with Windows PowerShell 01-5

Lesson 2
Finding and Learning Commands
Contents:
Question and Answers 6
Demonstration 6
01-6 Automating Administration with Windows PowerShell

Question and Answers


Question: Is there a way to specify multiple keywords when you search Help?

Answer: No. You are not technically using search keywords, you are using wildcard patterns, and only a
single pattern is accepted by the Help command. You can use additional commands to provide additional
filtering criteria, and you will learn about those commands later in this course.

Demonstration
Demonstration: Viewing Help

Demonstration Steps
1. In the Windows PowerShell console, run:

help dir

2. Discuss the basic Help for the Get-ChildItem command. Point out the
–recurse switch.
3. Run:

Get-Help Dir

4. Point out the difference between this output and the paged output of Help. You may need to reduce
the size of the console window to demonstrate the paging of the output, because if it is full screen,
the command may display the output in the single screen because it fits; as a result, there is no
paging. Also be aware that the content is otherwise the same.

5. To display the floating window help, run:

help dir –showwindow

6. To display the usage examples in the help, run:

help dir –example

7. If you have an appropriate host computer or virtual machine that has Internet access as mentioned in
the preparation steps, run
help dir –online to display the online help.

Demonstration: Finding Commands

Demonstration Steps
1. Run:

help *html*

2. Run:

Get-Command –verb new

3. Run:

help *restart*
Getting Started with Windows PowerShell 01-7

4. Run:

Get-Command *ipv4*

5. Run help *event*, and then run either help get-eventlog or help get-winevent. Notice that the
commands include a –ComputerName parameter than enables the commands to connect to a
remote computer.

Demonstration: Using “About” Files

Demonstration Steps
1. Run:

help about*

2. Run:

help about_aliases

3. Run:

help about_eventlogs -showwindow

4. Run:

help *beep*
01-8 Automating Administration with Windows PowerShell

Lesson 3
Running Commands
Contents:
Question and Answers 9
Demonstration 9
Getting Started with Windows PowerShell 01-9

Question and Answers


Question: Are –WhatIf and –Confirm supported by all commands that modify the system state or
configuration in some way?

Answer: No. Microsoft recommends that command authors support these parameters, but does not
enforce that support. Examine each command’s Help file to verify support for these parameters.

Demonstration
Demonstration: Using Show-Command

Demonstration Steps
1. Run:

Show-Command Get-Service

2. On the Default tab, enter BITS into the Name field.

3. Enter LON-DC1 into the ComputerName field.


4. Click Copy, and then click Close. In the Windows PowerShell console application, right-click to paste
the command.

Demonstration: Using -WhatIf and -Confirm

Demonstration Steps
1. To demonstrate a single object, run:

Stop-Service –Name BITS –WhatIf

2. To demonstrate multiple objects, run:

Stop-Service –Name * -WhatIf

3. Open Notepad.

4. Run:

Stop-Process –Name Notepad –Confirm

5. Answer yes to the prompt. Confirm that Notepad is no longer running.

6. To demonstrate multiple object confirmation, run:

Stop-Process –Name * -Confirm

7. Answer No to the first two prompts by typing N and pressing Enter (the default is Yes, so do not just
press Enter), and then answer No To All to halt the command by typing L and pressing Enter.

8. Run:

$ConfirmPreference = 'Low'

9. Run:

Start-Service –Name BITS


01-10 Automating Administration with Windows PowerShell

Notice that confirmation is now automatic. Answer No by typing N at the prompt.

10. Run:

Start-Service –Name BITS –confirm:$false

Notice that confirmation is suppressed.

11. To confirm that the BITS service is now running, run:

Get-Service –Name BITS

12. To return the setting to its default value, run:

$ConfirmPreference = 'High'

13. Run:

help Clear-EventLog

14. Point out the –WhatIf and –Confirm parameters in the Syntax part of the Help.
Getting Started with Windows PowerShell 01-11

Module Review and Takeaways


Best Practice
When you discover a new command, either by using Help or Get-Command, or by reading about the
command someplace, always take a moment to read the command’s Help file and learn a bit about its
additional capabilities.

Best Practice
Even familiar commands can gain new functionality in new versions of Windows PowerShell. Take several
minutes to read the Help files even of commands that you already know well from earlier versions, to see
what new features may exist.

Common Issues and Troubleshooting Tips


Common Issue Troubleshooting Tip

Help files contain only syntax section—no Run Update-Help to download the
description or examples. complete Help file content.

Cannot use Update-Help with computers From an Internet-connected computer, use


not connected to the Internet. Save-Help to download Help content to a
file share or removable storage. On the
unconnected computer, run Update-Help
and then specify the file share or removable
storage by using the –Source parameter.

Update-Help did not download all Help. Update-Help will download Help only for
modules that are located on your computer,
in a path that is listed in the PSModulePath
environment variable, and only if the
module has the necessary metadata to tell
Update-Help where updated Help files can
be located online. Not all Help may be
available in all languages, and Windows
PowerShell will resort to en-US (US English)
Help files if necessary.

Lab Review Questions and Answers


Question and Answers
Question: Why might you decide to use the console application instead of the ISE?

Answer: The console application supports transcripts in addition to multiline command entry and several
other Windows PowerShell features, whereas the ISE does not fully support all these features.

Question: Why might you configure alternative text colors in the ISE?

Answer: Some default ISE colors can be difficult to see, such as the default light gray used for curly braces
and other punctuation. Changing the colors can make these elements easier to see. This can help you
avoid errors.
01-12 Automating Administration with Windows PowerShell

Question: What is the main difference between Get-Help and Get-Command?

Answer: Get-Help searches for Help files, whereas Get-Command searches for commands. There is
frequently overlap between the two, but not every command will always have a Help file. Also, there are
Help files (the “About” files among them) that do not relate to a command.
Working with the Pipeline 02-1

Module02
Working with the Pipeline
Contents:
Lesson 1: Understanding the Pipeline 2 

Lesson 2: Selecting, Sorting, and Measuring Objects 4 

Lesson 3: Converting, Exporting, and Importing Objects 7 


Lesson 4: Filtering Objects Out of the Pipeline 10 

Lesson 5: Enumerating Objects in the Pipeline 12 

Module Review and Takeaways 14 


Lab Review Questions and Answers 15 
02-2 Automating Administration with Windows PowerShell

Lesson 1
Understanding the Pipeline
Contents:
Question and Answers 3
Demonstration 3
Working with the Pipeline 02-3

Question and Answers


Question: Where could you find additional documentation about an object’s members?

Answer: It depends on who wrote the command that produced the object. For most commands written
by Microsoft®, output objects are documented in the Microsoft Developer Network (MSDN) Library. Using
the object’s TypeName in an Internet search is frequently the fastest way to find the object’s
documentation, if documentation exists.

Demonstration
Demonstration: Pipeline Basics

Demonstration Steps
1. Run:

Get-Service

2. Run:

Get-Process

3. Run:

Get-Service | Out-File ServiceList.txt

4. To discover Out-GridView, run:

Help *grid*

5. Run:

Get-EventLog –LogName Security –Newest 5 | Out-GridView

6. To discover the type name (System.Diagnostics.Process), run :

Get-Process | Get-Member

7. To discover the MaxSpeed property, run:

Get-NetAdapter | Get-Member
02-4 Automating Administration with Windows PowerShell

Lesson 2
Selecting, Sorting, and Measuring Objects
Contents:
Question and Answers 5
Demonstration 5
Working with the Pipeline 02-5

Question and Answers


Question: Why might you use the –first parameter of Select-Object?

Answer: When you do not need the entire output of a command, selecting only the first rows can
sometimes improve performance. Select-Object is able to tell previous commands that no more data is
required. Some commands are then able to stop processing, reducing the total amount of time it takes
Windows PowerShell to complete the task.

Demonstration
Demonstration: Sorting Objects

Demonstration Steps
1. Run:

Get-Process | Sort-Object –Property ID

2. Run:

Get-Service | Sort-Object –Property Status

Point out that Stopped appears before Running because the property is stored as a number internally,
with zero (stopped) coming before 1 (running).

3. Run:

Get-EventLog –LogName Security –Newest 10 | Sort-Object –Property TimeWritten

4. Run:

Get-Service | Sort-Object –Property Name,Status

Demonstration: Measuring Objects

Demonstration Steps
1. Run:

Get-Service | Measure-Object

2. Run:

Get-Process | Measure-Object

3. Run:

Get-Process | Measure-Object –Property VM –Sum –Average

Demonstration: Selecting Objects

Demonstration Steps
1. Run:

Get-Process | Sort-Object –Property VM –Descending | Select-Object –First 10

2. Run:
02-6 Automating Administration with Windows PowerShell

Get-Date | Select-Object –Property DayOfWeek

3. Run:

Get-EventLog –Newest 10 –LogName Security | Select-Object –Property


EventID,TimeWritten,Message

Demonstration: Creating Calculated Properties

Demonstration Steps
1. Run:

Get-History

2. Run:

Get-History | Get-Member

3. Locate the StartExecutionTime and EndExecutionTime properties.

4. Run:

Get-History | Select-Object -Property


*,@{n='ExecutionTime';e={$PSItem.EndExecutionTime - $PSItem.StartExecutionTime}}

5. Run:

Get-History | Select-Object -Property


*,@{n='ExecutionTime';e={$PSItem.EndExecutionTime - $PSItem.StartExecutionTime}} |
Sort-Object –Property ExecutionTime –Descending
Working with the Pipeline 02-7

Lesson 3
Converting, Exporting, and Importing Objects
Contents:
Question and Answers 8
Demonstration 8
02-8 Automating Administration with Windows PowerShell

Question and Answers


Question: What other data forms might you want to convert data to or from?

Answer: There are many different forms. The .xls or .xlsx format is a common request, although Windows
PowerShell does not contain a native command for reading or writing those formats.

Demonstration
Demonstration: Converting and Exporting Objects

Demonstration Steps
1. Run:

Get-Process | ConvertTo-HTML

Because you used the verb ConvertTo, the data remains in the shell and displays on the screen.

2. Run:

Get-Process | ConvertTo-HTML | Out-File Procs.html

You must use this two-step approach because Windows PowerShell does not provide an Export-HTML
command.

3. Run:

Get-Service | ConvertTo-CSV

4. Run:

Get-Service | ConvertTo-CSV | Out-File Serv.csv

Or, run:

Get-Service | Export-CSV Serv.csv

Both commands will have the same result.

5. Run:

Notepad Serv.csv

Note how some data, such as dependent services, is missing. That is because a comma-separated value
(CSV) file cannot show hierarchical data or nested objects appropriately.

Demonstration: Importing Objects

Demonstration Steps
1. Run:

Get-Content Serv.csv

2. Run:

Import-Csv Serv.csv
Working with the Pipeline 02-9

Contrast this output with the output of the previous command.

3. Run:

Import-Csv Serv.csv | Sort Status,Name –Descending | Select Name,Status


02-10 Automating Administration with Windows PowerShell

Lesson 4
Filtering Objects Out of the Pipeline
Contents:
Question and Answers 11
Demonstration 11
Working with the Pipeline 02-11

Question and Answers


Question: Do you find $_ or $PSItem easier to remember and use?

Answer: This is obviously a personal opinion. $PSItem is new in Windows PowerShell 3.0, and so
experienced users frequently use $_ out of habit. $_ is obviously shorter and easier to type, but for many
beginning users it is more confusing than $PSItem. Both work the same way, and you will probably see
both in various online examples, books, and other resources. Many of the examples in Windows
PowerShell’s own Help files still use $_.

Demonstration
Demonstration: Filtering

Demonstration Steps
1. Run:

Get-SMBShare | Where Name –like '*$*'

2. Run:

Get-PhysicalDisk | Where-Object –FilterScript { $PSItem.HealthStatus –eq 'Healthy' }

3. Run:

Get-Volume | Where { $PSItem.DriveType –eq 'Fixed' –and $PSItem.FileSystem –eq 'NTFS'


}

4. Run:

Get-Verb | Where { $_.Verb –like 'c*' }


02-12 Automating Administration with Windows PowerShell

Lesson 5
Enumerating Objects in the Pipeline
Contents:
Question and Answers 13
Demonstration 13
Working with the Pipeline 02-13

Question and Answers


Question: If you have programming or scripting experience, does ForEach-Object look familiar to you?

Answer: The command is functionally similar to enumeration programming constructs present in many
programming and scripting languages. For example, in Microsoft Visual Basic®, the ForEach construct
provides a similar purpose. Windows PowerShell does have a ForEach scripting construct, although its
syntax differs from that of the ForEach-Object command.

Demonstration
Demonstration: Basic Enumeration

Demonstration Steps
1. Run:

Get-Service | ForEach Name

2. Run:

Get-EventLog –List | Where Log –eq 'System' | ForEach Clear

Demonstration: Advanced Enumeration

Demonstration Steps
1. Run:

Get-ItemProperty –Path HKCU:\Network\* | ForEach-Object –Process { Set-ItemProperty –


Path $PSItem.PSPath –Name RemotePath –Value $PSItem.RemotePath.ToUpper() }

2. Run:

Get-Process | ForEach-Object –Begin { Get-Date | Out-File Procs.txt } –Process {


$PSItem.Name | Out-File Procs.txt –Append }
02-14 Automating Administration with Windows PowerShell

Module Review and Takeaways


Best Practice
For best performance, remember to move filtering actions as close to the beginning of the command-line
as possible. Sometimes that may mean using a filtering capability of a regular command, instead of using
Where-Object.

Question: $_ and $PSItem were used several times in this module. Why might you decide to use one
over the other?

Answer: Both are functionally the same. $PSItem was introduced in Windows PowerShell 3.0 as an easier-
to-read alternative to $_, but $PSItem is not available in earlier versions of Windows PowerShell.
Therefore, scripts that have to maintain backward compatibility must continue to use $_. You are likely to
see $_ in examples written by other people (such as in online articles or blogs) for earlier versions, so you
should remember both $_ and $PSItem.

Real-world Issues and Scenarios


One aspect of Windows PowerShell that can be challenging is that frequently, you can achieve the same
result several different ways. Different people may select various techniques based on their experience,
but that does not necessarily make one technique better or worse than the others. Consider the following:
Get-Service | Select-Object -Property Name

Gsv | Select Name

Get-Service | ForEach Name

Get-Service | % { $_.Name }

Get-Service | ft name

In Windows PowerShell 3.0, these five commands produce the same result: a list of service names. As you
explore Windows PowerShell, and especially as you read examples written by other people or provided by
your instructor, you should be aware that there is not only one correct way to use Windows PowerShell.
Part of using the shell is being able to understand many approaches, arrangements of syntax, and
techniques.

Common Issues and Troubleshooting Tips


Common Issue Troubleshooting Tip

$_ does not work. $_ is a special placeholder and works only in


positions where the shell is programmed to
look for it. Examples include the script block
used in a calculated property expression, the
filter script for Where-Object, and the script
block used for ForEach-Object.

$_ is confusing to read. You can use the $PSItem variable instead.


This variable was introduced in Windows
PowerShell 3.0. $PSItem can be used in the
same positions as $_.
Working with the Pipeline 02-15

Lab Review Questions and Answers


Question and Answers
Question: Suppose that you wanted to produce output that included all of an object’s properties except
one. What would be the most efficient way to do that?

Answer: The Select-Object command has an –ExcludeProperty parameter. You would use it to list the
one property that you do not want included, and use –Property * to include the remaining properties.
Question: Could you use ConvertTo-CSV or Export-CSV to create a file that was delimited by using a
character other than a comma? For example, could you create a tab-delimited file?

Answer: Yes. Both commands have a –Delimiter parameter that changes the delimiter used for the file.
To specify a tab character, use "`t" (the double quotation marks are required).

Question: The HTML produced by ConvertTo-HTML looks very plain. The HTML standard offers a way to
specify visual styles for an HTML document. This is known as a cascading style sheet (CSS). Does the
command offer a way to attach a CSS?

Answer: Yes. You can either embed a style sheet by providing the appropriate HTML and CSS code to the
–Head parameter, or attach an external style sheet by using the –CssUri parameter.
Question: Do you prefer the basic or advanced syntax of Where-Object?

Answer: This is obviously a personal opinion. However, remember that you will probably encounter both
forms of syntax as you discover examples written by other Windows PowerShell users, such as in books or
on blogs.

Question: What is the difference between Select-Object and Where-Object?

Answer: They seem to offer similar functionality. However, Select chooses the properties that you want to
include in your output, and can choose objects from the beginning or the end of the collection. Where
can also choose objects. However, it does so based on criteria that you provide.

If you are familiar with any version of the Structured Query Language (SQL), remember that the SELECT
keyword chooses columns and the WHERE keyword chooses rows. These Windows PowerShell commands
are named similarly because they have similar purposes.

Question: In the first task of this lab, were you able to achieve the goal without using the Where-Object
command?

Answer: You should have been able to. The Get-ADUser command has –Filter and –SearchBase
parameters that provide the filtering functionality that you needed. Using Where-Object would be
inefficient and incorrect in this scenario.

Question: Do you prefer the basic or advanced syntax of ForEach-Object?

Answer: This is obviously a personal opinion. However, remember that you will probably encounter both
forms of syntax as you discover examples written by other Windows PowerShell users, such as in books or
on blogs.
02-16 Automating Administration with Windows PowerShell
Understanding How the Pipeline Works 03-1

Module03
Understanding How the Pipeline Works
Contents:
Lesson 1: Passing Data in the Pipeline By Value 2 

Lesson 2: Passing Data in the Pipeline By Property Name 5 

Module Review and Takeaways 9 


Lab Review Questions and Answers 9 
03-2 Automating Administration with Windows PowerShell

Lesson 1
Passing Data in the Pipeline By Value
Contents:
Question and Answers 3
Demonstration 3
Understanding How the Pipeline Works 03-3

Question and Answers


Question: Why do most commands that use the noun Object have an –InputObject parameter that
accepts objects of the type Object or PSObject?

Answer: Commands that use the noun Object are meant to work with any kind of input. Therefore, each
of them defines a parameter named –InputObject. That parameter is meant to receive any kind of object
from the pipeline, and therefore it accepts input of the type Object or PSObject, from the pipeline, by
using ByValue.

Demonstration
Demonstration: Passing Data ByValue

Demonstration Steps
1. In the Script Pane, in a blank script, type:

Get-Service –Name BITS | Stop-Service

2. Press Ctrl+I to show the Script Pane on top of the Console pane.

3. In the Console pane, run:

Get-Service | Get-Member

Show that the TypeName is ServiceController.


4. In the Console pane, run:

help Stop-Service –ShowWindow

5. In the Help window, show that the –InputObject parameter accepts objects of the type
ServiceController, from the pipeline, by using ByValue.
6. You should have determined that the objects produced by the first command in step 1 will be
attached to the –InputObject parameter of the second command.

7. Close the Help window.


Demonstration: Overriding the Pipeline

Demonstration Steps
1. Run:

"BITS","WinRM" | Get-Service

2. This command runs without error.

3. Run:

"BITS","WinRM" | Get-Service -Name BITS

4. This command generates an error.

5. Discuss how using the –Name parameter causes an error.

Demonstration: Parenthetical Commands


03-4 Automating Administration with Windows PowerShell

Demonstration Steps
1. Run:

"LON-CL1","localhost" | Out-File C:\Computers.txt

2. Run:

Get-Content C:\Computers.txt

3. Run:

Get-Service –ComputerName (Get-Content c:\Computers.txt)


Understanding How the Pipeline Works 03-5

Lesson 2
Passing Data in the Pipeline By Property Name
Contents:
Question and Answers 6
Demonstration 6
03-6 Automating Administration with Windows PowerShell

Question and Answers


Question: Can correct use of pipeline parameter binding reduce the need to use ForEach-Object?

Answer: Yes. For example, the Active Directory® user account demonstration that you saw could also be
accomplished by using enumeration:

Import-CSV Users.csv | ForEach-Object { New-ADUser –Name $_.Name –samAccountName


$_.samAccountName }
But when a command supports pipeline input, you can frequently use a less complex syntax:

Import-CSV Users.csv | New-ADUser

Demonstration
Demonstration: Passing Data ByPropertyName

Demonstration Steps
1. Run:

Import-CSV E:\Mod03\Democode\Users1.csv

Point out that the columns of the CSV file become properties, and each row of the CSV file
becomes an object.
2. Run:

Help New-ADUser –ShowWindow

Point out that most parameters of this command correspond to Active Directory® attributes. Also point
out that most parameters, such as –Title, -Department, -City, and so on, all accept pipeline input by using
ByPropertyName

3. Run:

Import-CSV E:\Mod03\Democode\Users1.csv | New-ADUser –WhatIf

Explain that this command would have created four new users having the appropriate attributes. Also
explain that this is not a real-world example. In a real organization, the CSV file would originate with a
Human Resources or Personnel department, which might not provide the correct format.

4. Run:

Import-CSV E:\Mod03\Democode\Users2.csv

Explain that this is a more realistic example. The person providing this file eliminated the
samAccountName field. That person might not have known what it was for, or might have thought that it
contained duplicate data. However, you can no longer use the file directly because it does not provide the
required samAccountName property.

5. Run:

Import-CSV E:\Mod03\Democode\Users2.csv | Select-Object –Property


*,@{n='samAccountName';e={$_.Name}} | New-ADUser

This command runs correctly. Select-Object was used to add the missing samAccountName property,
copying its value from the provided Name property.
Understanding How the Pipeline Works 03-7

6. Run:

Get-ADUser –filter *

Point out that the new user accounts exist. They are disabled because they were created without a
password. You can view this in the Enabled status, listed as False in the output for those newly created
accounts.

Demonstration: Expanding Property Values

Demonstration Steps
1. In the Windows PowerShell Integrated Scripting Environment (ISE), press Ctrl+I.

2. In the Console pane, run:

Get-ADComputer –filter *

This retrieves a list of computer objects. These are full objects, with several properties each.

3. In the Script Pane, type:

Get-Service –ComputerName (Get-ADComputer –filter *)

Explain that your goal is to display a list of services that are running on every computer in the domain.
4. In the Console pane, run:

Get-ADComputer –Filter * | Get-Member

Explain that the command produces objects of the type ADComputer, as shown by the output of Get-
Member.
5. In the Console pane, run:

Help Get-Service –ShowWindow

In the Help window, explain that the –ComputerName parameter accepts objects of the type String. Go
back to the Script Pane and explain that the parenthetical command is producing objects that are not of
the type String. Therefore, the command will not work. The parenthetical command is not producing the
kind of object that the parameter requires.

6. In the Console pane, run:

Get-ADComputer –Filter * | Select-Object –Property Name

Explain that this does select only the Name property. The –ComputerName parameter wants a name, and
the Name property contains a name.

7. In the Console pane, run:

Get-ADComputer –Filter * | Select-Object –Property Name | Get-Member

Explain that the output of Select-Object in this example is still an ADComputer object. It is not a string.

8. In the Console pane, run:

Get-ADComputer –Filter * | Select-Object –ExpandProperty Name


03-8 Automating Administration with Windows PowerShell

Explain that –ExpandProperty accepts a single property name, and it extracts the contents of that
property.

9. In the Console pane, run:

Get-ADComputer –Filter * | Select-Object –ExpandProperty Name | Get-Member

Explain that, by using –ExpandProperty, the output of Select-Object is now a string. That is the kind of
object the –ComputerName parameter expects.

10. In the Script Pane, change the parenthetical command to read:

(Get-ADComputer –Filter * | Select-Object –ExpandProperty Name)

Explain that this will retrieve every computer object from the domain, and extract the contents of their
Name properties as a string. Those strings will be given to the –ComputerName parameter.

11. Press F5 to run the command. You may see errors if every computer is not online or available.
However, the command will try to contact each one.
Understanding How the Pipeline Works 03-9

Module Review and Takeaways


Best Practice
It is easy to start using Windows PowerShell and not think about what the shell is doing for you. Always
take a moment to examine each command that you write, and think about what the shell will do. Think
about what objects will be produced by each command, and how those will be passed to the next
command.

Question: Because pipeline input binding is handled invisibly by the shell, it can be difficult to
troubleshoot. Are there any tools that can help you troubleshoot pipeline input?

Answer: Yes. The built-in Trace-Command command can analyze a command as it runs, and display
information about how data is attached to each parameter. Read the Help file, especially the examples, for
this command to learn more.

Real-world Issues and Scenarios


Sometimes, command authors do not realize how useful and important pipeline input can be, and they
do not create their parameters to accept pipeline input. All that you can do in those cases is submit a
request to the command author to support pipeline input in a future release.

Lab Review Questions and Answers


Question and Answers
Question: Why do some commands accept pipeline input for a parameter such as –ComputerName, but
other commands do not?

Answer: It depends completely on what the developer of the command decided. You cannot change
pipeline acceptance except to rewrite the command. In the case of a cmdlet, that would require you to
have the original source code, which may not be available for commercial cmdlets.

Question: Do you ever have to rely on pipeline input? Could you just rely on parenthetical commands?
Answer: You could just rely on parenthetical commands. However, they can become complex and
difficult to read. For example, consider this command that uses pipeline input:

Get-Process | Sort VM –Descending | Select –First 10


Now consider this version that uses only parenthetical commands:

Select –First 10 –InputObject (Sort –InputObject (Get-Process) –Property VM –Descending)

The first version is much easier to read.


03-10 Automating Administration with Windows PowerShell
Using PSProviders and PSDrives 04-1

Module04
Using PSProviders and PSDrives
Contents:
Lesson 1: Using PSProviders 2 

Lesson 2: Using PSDrives 4 

Module Review and Takeaways 6 


Lab Review Questions and Answers 6 
04-2 Automating Administration with Windows PowerShell

Lesson 1
Using PSProviders
Contents:
Question and Answers 3
Demonstration 3
Using PSProviders and PSDrives 04-3

Question and Answers


Question: What other kinds of PSProviders might exist as add-ins to the shell?

Answer: Microsoft® has created PSProviders for Active Directory Domain Services®, Microsoft SQL Server®
2012, Microsoft Internet Information Services (IIS), and many other products and technologies.
Independent software vendors (ISVs) can also create add-in PSProviders.

Demonstration
Demonstration: Working with Providers

Demonstration Steps
1. Run:

Get-PSProvider

2. Run:

Import-Module ActiveDirectory

3. Run:

Get-PSProvider

4. Run:

Help Registry
04-4 Automating Administration with Windows PowerShell

Lesson 2
Using PSDrives
Contents:
Question and Answers 5
Demonstration 5
Using PSProviders and PSDrives 04-5

Question and Answers


Question: If Get-Content displays the contents of a text file on the file system, how could you display the
contents of a built-in function like Help?

Answer: Windows PowerShell stores functions in the drive Function. Run Get-Content Function:\Help to
display the contents of that function.

Demonstration
Demonstration: Working with Drives and Items

Demonstration Steps
1. Run:

Cd C:\

2. Run:

New-PSDrive –Name WINDIR –Root C:\Windows –PSProvider FileSystem

3. Run:

Dir WINDIR:

4. Run:

New-Item –Path HKCU:\Software –Name Classroom

5. Run:

New-ItemProperty -Path HKCU:\Software\Classroom -Name Test -Value 1

6. Run:

Dir HKCU:\Software\Classroom
04-6 Automating Administration with Windows PowerShell

Module Review and Takeaways


Question: What is the advantage of managing something by using a PSProvider instead of commands?

Answer: A PSProvider can be dynamic. When a technology can be dynamically extended, a PSProvider
offers a good way to expose that technology when the commands needed cannot be known in advance.
For example, IIS can be extended by using add-ins. You cannot know in advance what add-ins will be
available or loaded, and so you cannot create commands for them all. A PSProvider can dynamically
adapt to what is currently installed. However, administration by using a PSProvider is less intuitive and less
discoverable than administration by using commands.

Real-world Issues and Scenarios


A parameter of Get-ChildItem does not work with a particular PSDrive. For example, ---Filter does not
work when listing information in a registry drive. This is a known issue, and happens because each
PSProvider has different capabilities. The Registry PSProvider does not support --
-Filter.

Common Issues and Troubleshooting Tips


Common Issue Troubleshooting Tip

A PSDrive that was present in the shell is Windows PowerShell always starts with the
no longer present. same default PSDrive mappings. If you
create a new mapping that is not persistent,
the mapping will not exist in other shell
sessions. It will not be present in any new
shell sessions. You must re-create the
mapping in each new session that you open.

Lab Review Questions and Answers


Question and Answers
Question: Of the PSProviders included with Windows PowerShell, which support the use of alternative
credentials?

Answer: The FileSystem and WSMan providers support the use of alternative credentials. Run Get-
PSProvider to see that information.

Question: Windows PowerShell 3.0 can make one kind of PSDrive visible in File Explorer. What kind of
drive is that, and how do you make it visible?

Answer: When you run New-PSDrive, the ---Persistent parameter will make a drive visible in Windows®
Explorer. This works correctly only when the drive name is a single letter and is mapped to a FileSystem
location.
Formatting Output 05-1

Module05
Formatting Output
Contents:
Lesson 1: Using Basic Formatting 2 

Lesson 2: Using Advanced Formatting 4 

Lesson 3: Redirecting Formatted Output 6 


Module Review and Takeaways 9 

Lab Review Questions and Answers 9 


05-2 Automating Administration with Windows PowerShell

Lesson 1
Using Basic Formatting
Contents:
Question and Answers 3
Demonstration 3
Formatting Output 05-3

Question and Answers


Question: Look at the full Help for one of the format commands. What parameter do they all use to
accept input from the pipeline?

Answer: All the format commands have an ---InputObject parameter, which accepts input from the
pipeline by using the ByValue technique.

Demonstration
Demonstration: Basic Formatting

Demonstration Steps
1. Run:

Get-Process | Format-Wide –Property ID

2. Run:

Get-Process | Format-Wide –Property ID –Column 5

3. Run:

Get-Process | Format-Wide –AutoSize

4. Run:

Get-Service | Format-List –Property Name,Status

5. Run:

Get-Process | Format-List –Property *

6. Run:

Get-EventLog –LogName Security –Newest 50 | Format-Table –Property


EventID,TimeWritten -AutoSize
05-4 Automating Administration with Windows PowerShell

Lesson 2
Using Advanced Formatting
Contents:
Question and Answers 5
Demonstration 5
Formatting Output 05-5

Question and Answers


Question: What custom column keys are allowed in Format-Table that are not allowed in the calculated
properties of Select-Object?

Answer: Because the formatting commands prepare objects for display on the screen, they support keys
that relate to visual display. These keys include formatString, align, and width.

Demonstration
Demonstration: Custom Table Columns

Demonstration Steps
Because of the length and complexity of these commands, please run them from E:\
Mod05\Democode\Custom.ps1.

Demonstration: Grouped Tables

Demonstration Steps
1. Run:

Get-Service | Format-Table –GroupBy Status

2. Run:

Get-Service | Sort Status | Format-Table –GroupBy Status


05-6 Automating Administration with Windows PowerShell

Lesson 3
Redirecting Formatted Output
Contents:
Question and Answers 7
Demonstration 7
Formatting Output 05-7

Question and Answers


Question: If you wanted to include a specified set of object properties in a CSV file, would you use
Select-Object or Format-Table?

Answer: You would use Select-Object, because its output can be piped to Export-CSV.

Demonstration
Demonstration: Examining Formatting Output

Demonstration Steps
1. Run:

Get-Process | Get-Member

Notice that the output displays a type name and familiar-looking members.

2. Run:

Get-Process | Select Name,ID | GM

Notice that the output type name is similar, and that fewer properties are listed.
3. Run:

Get-Process | Ft Name,ID | GM

Notice that the output is completely different from the previous examples.

4. Run:

Get-Process | Ft Name,ID | Export-CSV Procs.csv

5. Run:

Notepad procs.csv

Notice that the format objects, not the process objects, were converted to comma-separated value
(CSV) files.
Demonstration: Redirecting Formatted Output

Demonstration Steps
1. Run:

Get-Process |
Format-Table –Property Name,ID,@{n='VM';e={$PSItem.VM / 1KB};formatString='N2'}

2. Run:

Get-Process |
Format-Table –Property Name,ID,@{n='VM';e={$PSItem.VM / 1KB};formatString='N2'} |
Out-File C:\Procs.txt

3. Run:
05-8 Automating Administration with Windows PowerShell

Notepad C:\Procs.txt

Demonstration: Using Grid Views

Demonstration Steps
1. Run:

Get-Process | Out-GridView

2. Click the Id column header to sort the grid.

3. Click the Add criteria drop-down list and select ProcessName. Click Add.

4. In the empty text box, type svchost

5. Close the grid view.

6. In the Windows PowerShell console, run:

Get-Process | Format-Table | Out-GridView

The error means that the command cannot accept formatted output.
Formatting Output 05-9

Module Review and Takeaways


Best Practice
Always make sure that your command works correctly before you worry about how to format the output.
Formatting can be complex, and doing it last will help you avoid many common mistakes.

Question: Where might you use Out-GridView?

Answer: Out-GridView is useful when you have a script that will display output to end users. Because the
command produces a familiar looking user interface (UI), it may be a better option for some scenarios
than the text output produced by the shell’s format commands.

Real-world Issues and Scenarios


Although Windows PowerShell’s formatting commands are powerful, they are not intended to be a
complete report creation tool. If you are trying to produce complex reports, consider storing data in
Microsoft® SQL Server®, and using Microsoft SQL Server Reporting Services (SSRS). Microsoft SQL Server
2012 Express is free, and includes SSRS.

Common Issues and Troubleshooting Tips


Common Issue Troubleshooting Tip

Error when you try to create a custom The syntax for custom columns is difficult,
table column. and Windows PowerShell requires extra
attention to details. Make sure that curly
braces and quotation marks are correctly
paired. Make sure that semicolons and
commas are correctly positioned.

Lab Review Questions and Answers


Question and Answers
Question: If you redirected formatted output to a file, is there a command that would let you attach that
file to an email message?

Answer: Yes. The Send-MailMessage command can accept file attachments


05-10 Automating Administration with Windows PowerShell
Querying Management Information by Using WMI and CIM 06-1

Module06
Querying Management Information by Using WMI and CIM
Contents:
Lesson 1: Understanding WMI and CIM 2 

Lesson 2: Querying Data by Using WMI and CIM 4 

Lesson 3: Making Changes by Using WMI and CIM 7 


Module Review and Takeaways 9 

Lab Review Questions and Answers 9 


06-2 Automating Administration with Windows PowerShell

Lesson 1
Understanding WMI and CIM
Contents:
Question and Answers 3
Demonstration 3
Querying Management Information by Using WMI and CIM 06-3

Question and Answers


Question: Can you think of any situations where you would have to use WMI instead of CIM?

Answer: The only situation is when you have to query a remote computer that does not have Windows
PowerShell remoting enabled, and you do not want to create a CIM session that uses the DCOM protocol.

Demonstration
Demonstration: Finding Classes Documentation

Demonstration Steps
1. In a web browser, go to the Bing website (or use your preferred Internet search engine). In the search
field, enter Win32_BIOS.

2. In the search results, click Win32_BIOS class (Windows).

3. Explain that this MSDN webpage is the documentation page for the class. Review some of the class
properties.
06-4 Automating Administration with Windows PowerShell

Lesson 2
Querying Data by Using WMI and CIM
Contents:
Question and Answers 5
Demonstration 5
Querying Management Information by Using WMI and CIM 06-5

Question and Answers


Question: What are the advantages of creating and using CIM sessions instead of ad hoc connections?

Answer: If you are querying a computer one or more times in a short period of time, a CIM session offers
much better performance than ad hoc connections.

Demonstration
Demonstration: Listing Namespaces

Demonstration Steps
1. Run Get-WMIObject ---Namespace root ---List -Recurse | Select -Unique __NAMESPACE

2. Note the ROOT\CIMV2 namespace and the ROOT\SecurityCenter2 namespace. You will use this in
the next demonstration.

Demonstration: Listing Classes

Demonstration Steps
1. Run:

Get-WmiObject -Namespace root\SecurityCenter2 –List

Explain that the class names starting with two underscore characters (__) are system classes. System classes
can typically be ignored.

2. Run:

Get-CimClass –Namespace root\CIMv2 | Sort CimClassName

Explain that an alphabetical list can be useful when you have to validate a guess about a class name. For
example, if you think a class named Win32_Network might be useful, you can more easily discover
whether the class exists by using an alphabetical list.

Demonstration: Querying Instances

Demonstration Steps
1. Run:

Get-WmiObject –Class Win32_Service

2. Run:

Get-CimInstance –ClassName Win32_Process

3. Run:

Get-CimInstance –ClassName Win32_LogicalDisk –Filter "DriveType=3"

4. Run:

Get-CimInstance –Query “SELECT * FROM Win32_NetworkAdapter"

Demonstration: Using CIMSessions


06-6 Automating Administration with Windows PowerShell

Demonstration Steps
1. Run:

$s = New-CimSession –ComputerName LON-DC1

2. Run:

Get-CimInstance –CimSession $s –ClassName Win32_OperatingSystem

3. Run:

$s | Remove-CimSession
Querying Management Information by Using WMI and CIM 06-7

Lesson 3
Making Changes by Using WMI and CIM
Contents:
Question and Answers 8
Demonstration 8
06-8 Automating Administration with Windows PowerShell

Question and Answers


Question: What are some disadvantages of using ForEach-Object instead of one of the Invoke
commands to invoke a method?

Answer: ForEach-Object does not include ---WhatIf or ---Confirm parameters. When you use this
command to invoke a method, the method will always run, and you will not have any way to test your
command.

Demonstration
Demonstration: Finding Methods and Documentation

Demonstration Steps
1. Run:

Get-WmiObject –ClassName Win32_Service | Get-Member

Explain that the Change() method is one member of the class.


2. Run:

Get-WmiObject -Class Win32_Service | Get-Member | Where Name -eq 'Change' | Format-


List Name,Definition

3. In a web browser, go to the Bing website (or your preferred search engine).
4. Enter Win32_Service as the search term.

5. In the search results, click Win32_Service class (Windows).

6. You should be viewing the MSDN documentation page located here - http://msdn.microsoft.com/en-
us/library/aa394418(VS.85).aspx.

7. On the webpage, scroll down to the Methods section list and then click Change.

8. Explain that this method has 11 parameters. Review the parameters with the class.
Demonstration: Invoking Methods

Demonstration Steps
1. Run:

Invoke-CimMethod –ComputerName LON-DC1 –ClassName Win32_OperatingSystem –MethodName


Reboot

2. Right-click the lower-left corner of the screen, and then click Run.

3. Type MSPaint, click OK, and then verify that the MSPaint application opens.
4. In the Windows PowerShell console or ISE, run:

Get-WmiObject –Class Win32_Process –Filter "Name='mspaint.exe'" | Invoke-WmiMethod –


Name Terminate

5. Ensure that MSPaint closes.


Querying Management Information by Using WMI and CIM 06-9

Module Review and Takeaways


Best Practice
Use CIM commands when possible. Unlike WMI commands, the CIM commands offer better performance
and are the commands that Microsoft continues to develop and improve over time.

Question: What do you think is the most difficult part about working with WMI and CIM?

Answer: Discovering the class that you want is the most difficult part about these technologies. Without a
central directory and with inconsistent documentation, finding the class that will let you achieve a specific
task can be very difficult and time-consuming. Many administrators rely on Internet search engines and
Internet discussion forums to find classes.

Real-world Issues and Scenarios


Not all organizations have deployed Windows Management Framework 2.0 or newer versions and
enabled Windows PowerShell remoting. That means the CIM commands cannot be used for ad hoc
connections in those environments. Although you could create CIM sessions that use the DCOM protocol
in those environments, doing this requires additional steps. Many environments will continue to use the
WMI commands until remoting is enabled throughout their environment.

Tools
Another way to explore the repository is to use a graphical tool. One tool is the PowerShell
Scriptomatic, available at http://go.microsoft.com/fwlink/?LinkID=306152.

Common Issues and Troubleshooting Tips


Common Issue Troubleshooting Tip

‘‘RPC server not found This error indicates that either the computer cannot be reached on the
error’’ when you use network or the computer has a local firewall that is preventing RPC
WMI commands connections.

Errors when you use CIM WS-MAN has specific requirements for connectivity that include a
to connect to a remote requirement for mutual authentication. Between trusted computers in a
computer by using the domain, mutual authentication is automatic. Outside a domain, additional
WS-MAN protocol configuration is required. Module 9, ‘‘Managing Remote Computers,’’
provides more details about the additional configuration steps.

‘‘Access Denied’’ error Only members of a computer’s local Administrators group may remotely
when attempting to query information from that computer. You either need to open Windows
connect to a remote PowerShell by using an appropriate administrator user account, or provide
computer. an alternative credential when querying.

Lab Review Questions and Answers


Question and Answers
Question: One of your lab tasks directed you to query Win32_Product. Do you know of any
disadvantages when you use this class?
06-10 Automating Administration with Windows PowerShell

Answer: The class forces Windows Installer to revalidate all installed packages. On computers that have
many installed packages, the validation process can take a long time to complete and can have a negative
effect on performance.

Question: What are the main differences between WMI and CIM?

Answer: Both query the same repository, so both can return the same information and perform the same
tasks. The only difference is the protocol they use to communicate with remote computers.
Preparing for Scripting 07-1

Module07
Preparing for Scripting
Contents:
Lesson 1: Using Variables 2 

Lesson 2: Scripting Security 5 

Module Review and Takeaways 7 


Lab Review Questions and Answers 7 
07-2 Automating Administration with Windows PowerShell

Lesson 1
Using Variables
Contents:
Question and Answers 3
Demonstration 3
Preparing for Scripting 07-3

Question and Answers


Question: What happens to variables when you close the shell?

Answer: All variables are removed from memory when the shell is closed. Built-in variables are re-created
every time a new shell session is opened, but user-created variables are not re-created automatically.

Demonstration
Demonstration: Using Variables

Demonstration Steps
1. Run:

$x1 = 100

2. Run:

$procs = Get-Process

3. Run:

$procs[0].name

4. Run:

$procs | Sort VM –Descending

5. Run:

"The content of x1 is $x1"

6. Run:

$x2 = 100

7. Run:

$x1 * $x2

8. Run:

"$($procs[0].name) $($procs[0].cpu)”

9. Run:

"`$x2 contains $x2"

10. Run:

$procs.name

11. Run:

$procs[0] | Format-List *
07-4 Automating Administration with Windows PowerShell

12. Run:

$procs | Get-Member
Preparing for Scripting 07-5

Lesson 2
Scripting Security
Contents:
Question and Answers 6
Demonstration 6
07-6 Automating Administration with Windows PowerShell

Question and Answers


Question: What happens if you try to run a script that exists in the current directory, but you do not
provide an absolute or relative path?

Answer: The shell will display an error message. It will also display a warning indicating both that the
script does exist in the current folder and that you must provide a path to run the script.

Demonstration
Demonstration: Shell Security

Demonstration Steps
1. Run:

Get-Executionpolicy

Note the value returned.

2. Run:

Set-ExecutionPolicy Restricted

3. Answer Yes to the prompt by typing Y.

4. Run E:\Mod07\Democode\Test-NonCodesignedFile.ps1 and verify the script is not allowed to be


run.
5. Run:

Set-ExecutionPolicy RemoteSigned

6. Answer Yes to the prompt by typing Y.

7. Run E:\Mod07\demoCode\Test-CodesignedFile.ps1
8. Verify the file runs successfully.
Preparing for Scripting 07-7

Module Review and Takeaways


Best Practice
Use Group Policy to configure the execution policy in your environment. Group Policy offers a centralized
and easier way to consistently configure this important security setting.

Question: Do organizations typically use a single execution policy throughout their environment?

Answer: Most organizations do, because it simplifies management. Some organizations may leave the
execution policy set to the default value of Restricted on all computers except those where scripts need
to be run, such as administrator client computers and server computers.

Real-world Issues and Scenarios


If you try to change the local execution policy, but a Group Policy Object (GPO) is already applying an
execution policy setting, the GPO will override your local change. Windows PowerShell will display a
warning so that you know your change will not have any effect.

Common Issues and Troubleshooting Tips


Common Issue Troubleshooting Tip

Script will not run. Make sure that the execution policy permits
script execution. Also make sure that you
provide a path, not just a file name, to the
script.

Lab Review Questions and Answers


Question and Answers
Question: Will the execution policy remain in effect?

Answer: Yes, Set-ExecutionPolicy makes a persistent setting change. However, in class, if you are
directed to revert your virtual machine, your execution policy will return to the default setting, Restricted.
You may have to run Set-ExecutionPolicy again to return the setting to RemoteSigned.

Question: What is the best way to manage execution policy in an enterprise environment?

Answer: A Group Policy Object (GPO) provides centralized control, and can be targeted to the whole
organization, or to specific users and computers.
07-8 Automating Administration with Windows PowerShell
Moving from Command to Script to Module 08-1

Module08
Moving from Command to Script to Module
Contents:
Lesson 1: Moving from Command to Script 2 

Lesson 2: Moving from Script to Function to Module 5 

Lesson 3: Implementing Basic Error Handling 8 


Lesson 4: Using Basic Scripting Constructs 10 

Lesson 5: Exploring Other Scripting Features 12 

Module Review and Takeaways 14 


Lab Review Questions and Answers 14 
08-2 Automating Administration with Windows PowerShell

Lesson 1
Moving from Command to Script
Contents:
Question and Answers 3
Demonstration 3
Moving from Command to Script to Module 08-3

Question and Answers


Question: Do Write-Verbose and comment-based help serve the purpose of documenting a script and
its functionality?

Answer: They do, at least in part. Comment-based help provides documentation that is usable by
someone reading the script, in addition to by someone who is running the script. Verbose output can
serve the same purpose, by providing inline documentation of the various actions a script takes, as it takes
them.

Demonstration
Demonstration: Parameterizing a Working Command

Demonstration Steps
1. Run the following command to ensure that the local execution policy is correct:

Set-ExecutionPolicy RemoteSigned

2. Answer Yes to change the remote policy.

3. E:\Mod08\Democode\Param1.ps1 contains a working command. Run the command in the ISE to


demonstrate that the command works.
4. Point out the localhost computer name. This is obviously a value that will change when someone else
runs the command.

5. Open the file E:\Mod08\Democode\Param2.ps1 and view the modified script.

Demonstration: Adding Verbose Output

Demonstration Steps
1. Run the following command and click Yes to ensure that the local execution policy is correct:

Set-ExecutionPolicy RemoteSigned

2. If necessary, open E:\Mod08\Democode\Param2.ps1. This is the starting point.

3. Position your pointer at the end of line 5 and press Enter.

4. Add the following to line 6:

Write-Verbose "Connecting to $ComputerName"

5. Save the script as C:\Demo.ps1.

6. Close the file.

7. Press Ctrl+D. This changes the focus and therefore the active screen to the Console pane.

8. Type the following and press Enter:

Cd \

9. Type the following and press Enter:

.\Demo –Comp localhost

The script should run fine but with no verbose output.


08-4 Automating Administration with Windows PowerShell

10. Type the following and press Enter:

.\Demo –Comp localhost -Verbose

The script should run fine, and now there should be verbose output, including the line you entered in Step
4.

11. Close any opened files.

Demonstration: Adding Comment-Based Help

Demonstration Steps
1. Open E:\Mod08\Democode\Param3.ps1 in the ISE.

2. Insert the following before the first line of the script (or open E:\Mod08\Democode\Param4.ps1
instead):

<#
.SYNOPSIS
Retrieves network adapter information from a computer.
.DESCRIPTION
Uses CIM to retrieve information about physical adapters only.
.PARAMETER ComputerName
The name of the computer to query.
.EXAMPLE
.\Get-NetAdapterInfo.ps1 -ComputerName LON-DC1 -Verbose
#>

3. Save the script as C:\Demo.ps1. Overwrite the existing file.

4. Press Ctrl+D. This changes the focus, and therefore the active screen, to the console.
5. Type the following and press Enter:

Help C:\Demo

6. Close any open files.


Moving from Command to Script to Module 08-5

Lesson 2
Moving from Script to Function to Module
Contents:
Question and Answers 6
Demonstration 6
08-6 Automating Administration with Windows PowerShell

Question and Answers


Question: How could you set up your environment so that a set of script modules could be shared
between yourself and your coworkers?

Answer: You could store your modules in a shared folder on a file server. By adding the shared folder
path to the PSModulePath environment variable on your coworkers’ computers, everyone’s Windows
PowerShell sessions would be able to locate and load the modules as needed.

Demonstration
Demonstration: Testing the Function

Demonstration Steps
1. Open E:\Mod08\Democode\Function1.ps1.

2. On line 27, add the following:

Get-NetAdaptInfo –comp localhost

3. Press Ctrl+S to save the file.

4. Press F5 to run the script.

5. Close any open files.


Demonstration: Creating a Script Module

Demonstration Steps
1. Open E:\Mod08\Democode\Function2.ps1.
2. Delete line 27.

3. Press Ctrl+D.

4. Type the following commands, pressing Enter after each line:

Cd $home
Cd Documents
MkDir WindowsPowerShell
Cd WindowsPowerShell
MkDir Modules
Cd Modules
MkDir MyTools

5. On the File menu, click Save As.

6. In the File name box, type


C:\Users\Administrator.ADATUM\Documents\WindowsPowerShell\Modules\MyTools\MyTool
s.psm1, and then press Enter.

7. Close the file.

Demonstration: Adding and Using Debugging Breakpoints

Demonstration Steps
1. Open E:\Mod08\Democode\Function3.ps1.

2. On line 19, add the following:


Moving from Command to Script to Module 08-7

Write-Debug "About to query $ComputerName"

3. On the File menu, click Save As.

4. In the File name box, type


C:\Users\Administrator.ADATUM\Documents\WindowsPowerShell\Modules\MyTools\MyTool
s.psm1, and then press Enter.

5. In the Confirm Save As dialog box, click Yes.


6. Press Ctrl+D to switch to the Console pane.

7. Type the following and then press Enter (because the module may not be loaded, this command may
produce an error that you may ignore):

Remove-Module MyTools

8. Type the following and press Enter:

Get-NetAdaptInfo –comp localhost

9. Type the following and press Enter:

Get-NetAdaptInfo –Debug –Comp localhost

You should receive a debug prompt asking you whether you want to continue with the operation.
If you do not receive the prompt you should import the module again by typing:

Import-Module MyTools

Then remove the module by typing:

Remove-Module MyTools

And then continue from step 8 again.


10. Press S to suspend the operation.

11. Type the following and press Enter:

$ComputerName

12. Run Exit.

You should receive a prompt asking you to confirm whether you want to continue with the operation.

13. Press Y.
08-8 Automating Administration with Windows PowerShell

Lesson 3
Implementing Basic Error Handling
Contents:
Question and Answers 9
Demonstration 9
Moving from Command to Script to Module 08-9

Question and Answers


Question: The Try…Catch construct was introduced in Windows PowerShell 2.0. An earlier construct was
introduced in Windows PowerShell 1.0, and is still supported in Windows PowerShell 3.0. Do you know
what that older construct is?

Answer: It is the Trap construct. You may still see it in online examples from several years ago, and some
Windows PowerShell users may still use it. It is a less efficient construct than Try…Catch, and is more
difficult to plan, write, and debug. As a best practice, try to avoid Trap in new scripts that you write.

Demonstration
Demonstration: Error Actions

Demonstration Steps
1. Run the following command that outputs and error then continues to completion:

Get-WmiObject -Class Win32_BIOS -ComputerName LON-CL1,BAD,LON-CL1 –ErrorAction


Continue

2. Run the following command that does not output the error and continues to completion:

Get-WmiObject -Class Win32_BIOS -ComputerName LON-CL1,BAD,LON-CL1 –ErrorAction


SilentlyContinue

3. Run the following command that prompts for an action when it encounters an error.

Get-WmiObject -Class Win32_BIOS -ComputerName LON-Cl1,BAD,LON-CL1 –ErrorAction


Inquire

4. Run the following command that stops when it encounters an error:

Get-WmiObject -Class Win32_BIOS -ComputerName LON-CL1,BAD,LON-CL1 –ErrorAction Stop

Demonstration: Using Try...Catch

Demonstration Steps
 Run the script E:\Mod08\Democode\ErrorAction2.ps1.

Demonstration: Adding Error Logging

Demonstration Steps
 Run E:\Mod08\Democode\ErrorAction3.ps1.
08-10 Automating Administration with Windows PowerShell

Lesson 4
Using Basic Scripting Constructs
Contents:
Question and Answers 11
Demonstration 11
Moving from Command to Script to Module 08-11

Question and Answers


Question: Are you familiar with any scripting language constructs from other scripting languages that
might also be present in Windows PowerShell?

Answer: Windows PowerShell does feature scripting language constructs other than the ones covered in
this lesson. This includes several than will be covered in the next lesson. Windows PowerShell does not
feature as large a scripting language as languages such as Microsoft Visual Basic® Scripting Edition
(VBScript), Perl, or Python. Instead, Windows PowerShell relies on its built-in and add-in commands to
provide more functionality.

Demonstration
Demonstration: The If Construct

Demonstration Steps
 Run E:\Mod08\Democode\If.ps1.

Demonstration: The ForEach Construct

Demonstration Steps
 Run E:\Mod08\Democode\ForEach.ps1.

The script starts by creating an array of four computer names. Two of those names are known to be
incorrect.
The script enumerates through those so that only one computer name is being processed at a time. That
technique makes sure that Get-WMIObject is working on only one target at a time. When the command
encounters an error, it can stop processing, display a message, and move on to the next computer name.
08-12 Automating Administration with Windows PowerShell

Lesson 5
Exploring Other Scripting Features
Contents:
Question and Answers 13
Moving from Command to Script to Module 08-13

Question and Answers


Question: The main purpose for PSBreakpoints is to help debug scripts. You have also learned about the
Write-Debug command, which serves a similar purpose. What other approaches to debugging are you
familiar with?

Answer: You might be familiar with editors that provide built-in, visual debugging tools. The Windows
PowerShell ISE host application provides some visual representations for PSBreakpoints. Editors created by
independent software vendors (ISVs) can provide similar or additional capabilities.
08-14 Automating Administration with Windows PowerShell

Module Review and Takeaways


Best Practice
As you start to write functions, take the time to format commands and code in the correct way. Every time
that you begin a new construct, indent the contents of that construct. This technique helps make it
visually clearer which code belongs to the construct to make both maintenance and debugging easier.

Question: What kinds of tasks do you want to automate immediately using a script module?

Answer: This is an open-ended question. However, the easiest tasks to automate are usually the ones that
are performed manually several times each day or week. Creating new user accounts, archiving files, and
similar tasks are all good candidates.

Real-world Issues and Scenarios


As you write functions, remember that each function should produce as output only one kind of object. If
you have to have a function to combine information from several sources, that information should be
combined into a custom object that can hold all the information that you want. Creating custom objects is
beyond the scope of this course. However, you can start by looking at the New-Object command in
Windows PowerShell.

Common Issues and Troubleshooting Tips


Common Issue Troubleshooting Tip

A script module cannot be found by Make sure that the script module file is in
Windows PowerShell. the correct location. The PSModulePath
environment variable lists the acceptable
locations. Within those locations, you must
create a folder than has the module name,
and the module itself must be located in
that folder. The module file name must be
the same as that folder name, and the
module file name extension must be .psm1.

Lab Review Questions and Answers


Question and Answers
Question: What are some advantages of using comment-based help to document a script?

Answer: Comment-based help is easy to add. Normal Windows PowerShell Help files are external to the
script, and are written in a complex XML format. Comment-based help is included inside the script, and
consists of English keywords and basic text.

Question: If you have previous experience in scripting or programming, does Write-Debug work like
other debuggers you have used?

Answer: Probably not. Write-Debug is a very simplistic debugging tool. One advantage of this command
is that debug breakpoints stay with your script regardless of where you move or copy your script to.
However, the command is not as flexible as true debugging breakpoints. Windows PowerShell does
support true debugging breakpoints, and you will learn about them later in this module.
Moving from Command to Script to Module 08-15

Question: In one of the demonstrations, you saw an example of how to add error logging to a script. That
example used a static file name. In a production environment, a user might want the ability to specify the
name of the file where errors would be logged. How could you provide that ability?

Answer: You could add a parameter to a function to let the user specify a file name. You could provide a
default value for that parameter so that users would not be required to specify a file name. You might also
include verbose output to notify the user of the file name that was being used.

Question: What if you need to write a function whose output combines information from multiple
sources?
Answer: Windows PowerShell provides a means to accomplish this, but it will not be covered in this
course. You can read the Help for New-Object to obtain some of the information needed to accomplish
this task.
08-16 Automating Administration with Windows PowerShell
Administering Remote Computers 09-1

Module09
Administering Remote Computers
Contents:
Lesson 1: Using Basic Remoting 2 

Lesson 2: Using Advanced Remoting Techniques 4 

Lesson 3: Using Remoting Sessions 6 


Module Review and Takeaways 10 

Lab Review Questions and Answers 11 


09-2 Automating Administration with Windows PowerShell

Lesson 1
Using Basic Remoting
Contents:
Question and Answers 3
Demonstration 3
Administering Remote Computers 09-3

Question and Answers


Question: Why would an administrator decide to use remoting instead of managing a computer directly?

Answer: Sometimes, a computer might not be physically available. Computers in geographically distant
locations, for example, might be more easily managed remotely.

Question: What are some security concerns with remoting?

Answer: Remoting does require that credentials be delegated across the network, and remoting offers
expanded reach and capability for administrators. Both capabilities can cause concerns for some
organizations. However, remoting offers several features that enable organizations to help secure it, to
monitor it, and to audit it. Remoting does not give administrators additional permissions. Instead, it gives
them a more efficient way to exercise the permissions that they already have.

Demonstration
Demonstration: Enabling and Using Remoting

Demonstration Steps
1. Ensure you are signed into the 10961B-LON-CL1 virtual machine as Adatum\Administrator with
password Pa$$w0rd.

2. To ensure you have the correct execution policy in place, run:

set-executionPolicy RemoteSigned

3. Answer Yes to confirm the Execution Policy Change.


4. Run:

Enable-PSremoting

If you receive an error about a network connection being Public, run Enable-PSremoting ---SkipNetwork
instead. Point out the error to students; it is an error they’ll see a lot.
5. Click 'Yes' or press Y to confirm all dialog boxes.

6. Run:

Enter-PSSession --
-ComputerName LON-DC1

7. Run:

Get-Process

8. Run:

Exit-PSSession

9. Run:

Invoke-Command ---ComputerName LON-CL1,LON-DC1 ---ScriptBlock { Get-EventLog --


-LogName
Security --
-Newest 10 }
09-4 Automating Administration with Windows PowerShell

Lesson 2
Using Advanced Remoting Techniques
Contents:
Question and Answers 6
Demonstration 6
Administering Remote Computers 09-5

Question and Answers


Question: Why might you configure remoting to use ports other than the defaults?

Answer: In most cases, you would not do so. The best reason to configure remoting to use different ports
is when your organization uses an application that has to use the same ports.

Demonstration
Demonstration: Sending Local Variables to a Remote Computer

Demonstration Steps
1. To demonstrate how the data in a variable might be provided by a user, run:

$quantity = Read-Host "Query how many log entries?"

2. Run:

Invoke-Command ---ArgumentList $quantity ---ComputerName LON-DC1 ---ScriptBlock { Param($x)


Get-EventLog --
-LogName Security --
-newest $x }

You should be prompted for a number of log entries that you want to view. Enter any desired value (for
example, 5), and press Enter.

You should be able to view the number of entries you specified for the security log.
09-6 Automating Administration with Windows PowerShell

Lesson 3
Using Remoting Sessions
Contents:
Question and Answers 8
Demonstration 8
Administering Remote Computers 09-7

Question and Answers


Question: What are some potential operational concerns for sessions?

Answer: Because sessions are persistent, one concern is that lots of administrators might open many
sessions to a single server. That could potentially create a large amount of processing and memory
overhead on the server. This concern can be lessened by configuring remoting options appropriately to
limit the number of sessions one administrator can create, and limiting the total number of administrators
who may create concurrent sessions on a server.

Demonstration
Demonstration: Using Sessions

Demonstration Steps
1. On the LON-CL1 virtual machine, run:

$dc = New-PSSession --
-ComputerName LON-DC1

2. Run:

$all = New-PSSession ---ComputerName LON-DC1,LON-CL1

3. Run:

Get-PSSession

4. Run:

$dc

5. Run:

Enter-PSSession --
-Session $dc

6. Run:

Get-Process

7. Run:

Exit-PSSession

8. Run:

$dc

9. Run:

Invoke-Command ---Session $all --


-ScriptBlock { Get-Service | Where { $_.Status ---eq 'Running' }}

10. Run:

$dc | Remove-PSSession

11. Run:
09-8 Automating Administration with Windows PowerShell

Get-PSSession

12. Run:

Get-PSSession | Remove-PSSession

Demonstration: Disconnected Sessions

Demonstration Steps
1. Run:

$dc = New-PSSession --
-ComputerName LON-DC1

2. Run:

Disconnect-PSSession --
-Session $dc

3. Run:

Get-PSSession --
-ComputerName LON-DC1

4. Run:

Get-PSSession --
-ComputerName LON-DC1 | Connect-PSSession

5. To confirm that the session is available, run:

$dc

6. Run:

Remove-PSSession ---Session $dc

Demonstration: Implicit Remoting

Demonstration Steps
1. On 10961B-LON-CL1, run:

$dc = New-PSSession LON-DC1

2. Run:

Get-Module --
-PSSession $dc --
-ListAvailable

3. Run:

Import-Module --
-PSSession $dc --
-Name ActiveDirectory ---Prefix Rem

4. Run:

Help Get-RemADUser

Be aware that the server may not have updated Help, so the Help you retrieve may be truncated and
include only the Syntax section.

5. To see a list of all domain users, run:


Administering Remote Computers 09-9

Get-RemADUser --
-filter *

6. To close the session, run:

$dc | Remove-PSSession

7. Run:

Get-RemADUser

Notice that an error is displayed because the command is no longer available through implicit remoting.
09-10 Automating Administration with Windows PowerShell

Module Review and Takeaways


Best Practice
Always consider the security implications of opening remoting too much. The default configuration is
tightly locked down and provides a good balance of ease-of-use and security/privacy; make sure that,
before changing that default configuration, you have explored all the possible ramifications.

Real-world Issues and Scenarios


Many organizations express concerns about remoting’s security, and frequently decide to disable it.
remoting is just as secure as Remote Desktop Protocol, and in most ways is more secure and more
controllable than the many protocols (such as RPCs) that it tries to replace. As of Windows Server 2012,
remoting is required: native tools such as Server Manager rely on remoting to configure even the local
computer. IT security personnel should take the time to thoroughly understand remoting before just
deciding to disable it, as disabling it deprives administrators of a valuable management tool, frequently
requiring them to take less-secure workaround measures to restore lost functionality.
There is also misplaced concern over the CredSSP protocol, that Microsoft describes as an increased
security risk because it enables the delegation of credentials to remote computers, and if those computers
are compromised then the credential could also be compromised. The key phrase is ‘‘if those computers
are compromised,’’ reinforcing the fact that only trusted, managed, secured computers should be enabled
for CredSSP delegation. This concern is why delegating to a wildcard character such as * is incorrect doing
this would allow delegation to any computer. This includes untrusted, unmanaged, unsecured
computers and that is where the security risk lies.

Common Issues and Troubleshooting Tips


Common Issue Troubleshooting Tip

General problems using remoting. Remoting is a complex, multilayer set of


technologies, and troubleshooting can be
difficult. Secrets of Windows PowerShell
remoting, a free ebook at
www.PowerShellBooks.com, contains a
chapter on troubleshooting, including how to
enable diagnostic trace logs.

Remoting will not enable on a client This frequently occurs because of a network
computer. connection being set to Public, and
specifically when the client has workstation-
class virtualization software installed (which
can create many virtual network adapters).
Consider running Enable-PSremoting ---
SkipNetworkProfileCheck to enable
remoting.
Administering Remote Computers 09-11

Lab Review Questions and Answers


Question and Answers
Question: Would it be possible to use remoting to connect to a client computer and run an application
that the interactive user of that computer could see?

Answer: Not easily. Windows is a mutliuser operating system, and enforces strict boundaries between
users of the same computer. When you connect through remoting, you are connected to a user session
that is different from the user session of any other users who may be using the same computer. Trying to
run an application would just run it under your own session, invisible to other users. Running a graphical
application such as Notepad will make Windows PowerShell stop responding, because remoting cannot
display a graphical application. You can press Ctrl+C to end the graphical application and restore the shell
prompt.

Question: What are some benefits offered by implicit remoting?

Answer: One benefit is that administrators do not have to install administrative tools such as PowerShell
commands on their local computers. Instead, they can connect to a server or other computer that already
has the tools, and use them as if they were installed locally.

Another benefit is that access to tools can be more centrally monitored and controlled. By keeping
PowerShell commands on a smaller number of computers, the commands can also be more easily
updated as needed.
09-12 Automating Administration with Windows PowerShell
Putting it All Together 10-1

Module10
Putting it All Together
Contents:

Module Review and Takeaways 2 

Lab Review Questions and Answers 2 


10-2 Automating Administration with Windows PowerShell

Module Review and Takeaways


Best Practice
Always try to test commands in the console before adding them to a script. In this manner, you have to
write and debug only one command at a time. This makes it easier to assemble a working, bug-free script.

Common Issues and Troubleshooting Tips


Common Issue Troubleshooting Tip

One computer cannot connect to Find what communications protocol is being


another. used. For example, Ping.exe uses the ICMP
protocol that a firewall may be blocking.
Windows PowerShell Remoting uses WS-
MAN that is permitted by default in Windows
Server 2012. Other commands might use
remote procedure calls (RPCs), Windows
Management Instrumentation (WMI), or
other protocols, one or more of which might
not be allowed by a firewall, or might not be
enabled on the remote computer.

An extracted property value is not a Windows PowerShell does lots of behind the
string. scenes manipulation to data to try to make it
behave consistently, but sometimes it cannot
do everything. In your lab, you were
instructed to extract a computer’s IP address
from a DHCP lease object. The resulting IP
address is still seen by the shell as an array of
objects (with each character in the IP address
being a single object). Putting that into
double quotation marks $OldIPAddress =
"$OldIPAddress" forces the shell to parse
out the whole address and to then store it as
a single string.

Lab Review Questions and Answers


Question and Answers
Question: Why was it necessary to modify TrustedHosts?

Answer: Because the Server Core computer was not at first in the domain, and therefore had no context
for the mutual authentication typically required by Remoting.

Question: Why was it necessary to use the param() block and ---ArgumentList with Invoke-Command?

Answer: Because the information that we needed to pass to the remote computer was in variables, but
we could not include those variables directly in the ---ScriptBlock parameter value because the variables
themselves would have no meaning on the remote computer.
Using Background Jobs and Scheduled Jobs 11-1

Module11
Using Background Jobs and Scheduled Jobs
Contents:
Lesson 1: Using Background Jobs 2 

Lesson 2: Using Scheduled Jobs 5 

Module Review and Takeaways 8 


Lab Review Questions and Answers 8 
11-2 Automating Administration with Windows PowerShell

Lesson 1
Using Background Jobs
Contents:
Question and Answers 3
Demonstration 3
Using Background Jobs and Scheduled Jobs 11-3

Question and Answers


Question: What are some tasks that you might want to run in the background?

Answer: Any long-running task is a good candidate for running in the background. Also remember that
background jobs can run in parallel. That makes background jobs a good way for a script to start several
tasks that can run concurrently. The script can start the jobs and wait until they all complete before
proceeding.

Demonstration
Demonstration: Using Background Jobs

Demonstration Steps
1. On LON-CL1, run:

Enable-PSRemoting

Respond Yes by typing Y at each prompt.


2. Run:

Start-Job ---ScriptBlock { Dir C:\ -Recurse } --


-Name LocalDir

3. Run:

Invoke-Command ---ScriptBlock { Get-EventLog ---LogName Security --


-Newest 100 } --
-
ComputerName LON-CL1,LON-DC1 ---JobName RemoteLogs

4. Run:

Get-Job

5. Run:

Get-Job --
-Name LocalDir | Stop-Job

6. Run:

Receive-Job --
-Name LocalDir

7. Run:

Remove-Job --
-Name LocalDir

8. Run:

Get-Job

Repeat this step until the RemoteLogs job shows a status of Completed

9. Run:

Get-Job --
-Name RemoteLogs | Select --
-ExpandProperty ChildJobs

Remember the job ID number that corresponds to the LON-DC1 job.


11-4 Automating Administration with Windows PowerShell

10. Run:

Get-Job --
-ID <id> | Receive-Job ---Keep

Replacing <id> with the job ID number you remembered from the previous step.

11. Run:

Receive-Job --
-Name RemoteLogs

12. Run:

Remove-Job --
-Name RemoteLogs
Using Background Jobs and Scheduled Jobs 11-5

Lesson 2
Using Scheduled Jobs
Contents:
Question and Answers 6
Demonstration 6
11-6 Automating Administration with Windows PowerShell

Question and Answers


Question: Why might you use Register-ScheduledJob from the PSScheduledJob module instead of a
command in the ScheduledTasks module?

Answer: The ScheduledTasks module is not designed to retrieve job results. It is designed to manage the
task objects in the Windows Task Scheduler. The commands in PSScheduledJob manage a kind of job
that combines the abilities of the Windows Task Scheduler with Windows PowerShell manageability.

Demonstration
Demonstration: Using Scheduled Jobs

Demonstration Steps
1. Run:

Import-Module PSScheduledJob

2. Run:

Get-Job | Remove-Job

You may see an error here stating that the directory name C:\Users\.....\PowerShell\ScheduledJobs is
invalid. This will appear if there are no defined scheduled jobs and is expected. We run the remove-Job
command here to clear the jobs before proceeding with the next steps
3. Run:

$trigger = New-JobTrigger --
-Once --
-At (Get-Date).AddMinutes(2)

4. Run:

Register-ScheduledJob --
-Trigger $trigger --
-Name DemoJob --
-ScriptBlock { Get-EventLog ---LogName
Application }

5. Run:

Get-ScheduledJob | Select --
-Expand JobTriggers

Notice the Time

6. Run:

Get-ScheduledJob

Wait until after the time that was displayed in the previous step.

7. Run:

Get-Job

8. Run:

Receive-Job --
-Name DemoJob

9. Run:
Using Background Jobs and Scheduled Jobs 11-7

Get-Job --
-Name DemoJob | Remove-Job
11-8 Automating Administration with Windows PowerShell

Module Review and Takeaways


Question: What is the main difference between a background job and a scheduled job?

Answer: A background job runs only while Windows PowerShell is running. A scheduled job can run even
if the shell is not running, and you can still use the shell to retrieve job results.

Real-world Issues and Scenarios


Remember that scheduled jobs are defined, stored, and managed locally. There is no means of central
scheduled job management. For that reason, you should be careful to document job definitions. In large
environments, you may prefer to use a centralized job management solution, such as Microsoft System
Center Orchestrator.

Common Issues and Troubleshooting Tips


Common Issue Troubleshooting Tip

The ScheduledTasks module is not This module is a feature of Windows 8 and


available. Windows Server 2012 and is not available
on earlier versions of the operating system.
The PSScheduledJob module is a feature
of Windows PowerShell 3.0 and should be
available on any computer where that
version of the shell is installed.

Lab Review Questions and Answers


Question and Answers
Question: Get-CIMInstance does not have an ---AsJob parameter. Why? How would you use it in a job?
Answer: Microsoft is moving toward a standardized use pattern where Invoke-Command is used to run
commands on remote computers, and to manage that process in the background. You can use Get-
CIMInstance inside the script block of Invoke-Command, or inside the script block for Start-Job.

Question: What are some potential performance concerns about background jobs?

Answer: Each background job requires a Windows PowerShell runspace, meaning each job will consume
both CPU and memory while running. Job results are stored in memory, meaning jobs that produce a
large amount of output can use a large amount of memory until the results are received and the job is
removed.

Question: Is it possible to create a scheduled job without creating a job option object?

Answer: Yes. The ---ScheduledJobOption parameter of Register-ScheduledJob is optional. You need to


create a scheduled job option only if you require one of its features.
Using Profiles and Advanced Windows PowerShell Techniques 12-1

Module12
Using Profiles and Advanced Windows PowerShell
Techniques
Contents:
Lesson 1: Using Advanced Windows PowerShell Techniques 2 

Lesson 2: Creating Profile Scripts 6 


Lesson 3: Working with Alternative Credentials 8 

Module Review and Takeaways 10 

Lab Review Questions and Answers 10 


12-2 Automating Administration with Windows PowerShell

Lesson 1
Using Advanced Windows PowerShell Techniques
Contents:
Demonstration 3
Using Profiles and Advanced Windows PowerShell Techniques 12-3

Demonstration
Demonstration: Strings, Dates, and Operators

Demonstration Steps
1. Run:

$x = "Windows PowerShell"

2. Run:

$x.ToUpper()

3. Run:

$x.ToLower()

4. To show that the original value in $x is unchanged, run:

$x

5. Run:

$x.Replace("o","***")

6. Run:

$x.Length

7. Run:

$x.Substring(8,5)

8. Run:

$x -replace "o",'-'

9. Run:

$today = Get-Date

10. Run:

$today

11. Run:

$today.DayOfWeek

12. Run:

$today.AddDays(-30)

13. Run:

$today.ToShortDateString()
12-4 Automating Administration with Windows PowerShell

14. Run:

[datetime]$mydate = "1/1/1999"

15. Run:

$mydate.DayOfWeek

16. Run:

Get-CimInstance -ClassName Win32_OperatingSystem | Select


@{n='LastStartDate';e={$PSItem.LastBootUpTime.ToShortDateString()}}

17. Run:

Get-WmiObject -Class Win32_OperatingSystem | Select


@{n='LastStartDate';e={$PSItem.ConvertToDateTime($PSItem.LastBootUpTime).ToShortDateString(
)}}

18. Run:

$servicenames = Get-Service | Select -Expand Name

19. Run:

$servicenames -contains "WinRM"

20. Run:

"MSSQLServer" -in $servicenames

21. Run:

"192.168.12.15" -match "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"

Demonstration: Setting Default Parameter Values

Demonstration Steps
1. Run:

$PSDefaultParameterValues = @{"Get-CimInstance:ComputerName"="LON-DC1"}

2. Run:

$PSDefaultParameterValues.Add("Get-CimInstance:ClassName","Win32_BIOS")

3. Run:

$PSDefaultParameterValues

4. Run:

Get-CimInstance

5. Run:

Get-CimInstance -ComputerName localhost


Using Profiles and Advanced Windows PowerShell Techniques 12-5

Note: You will need to enable remoting by typing WinRM qc in the Windows PowerShell console and
accept the default values for this command to run successfully.

6. Run:

$PSDefaultParameterValues.Remove("Get-CimInstance:ClassName")

7. Run:

$PSDefaultParameterValues

8. Run:

$PSDefaultParameterValues = @{}
12-6 Automating Administration with Windows PowerShell

Lesson 2
Creating Profile Scripts
Contents:
Demonstration 7
Using Profiles and Advanced Windows PowerShell Techniques 12-7

Demonstration
Demonstration: Creating a Profile Script

Demonstration Steps
1. In the console, run ISE.

2. In the console pane, run:

Set-ExecutionPolicy RemoteSigned

3. Click Yes to confirm the Execution Policy Change dialog box.

4. In the ISE, press Ctrl+N.

5. In the Script Pane, enter:

Import-Module ActiveDirectory
Cd C:\

6. Press Ctrl+S.

7. In the tree view on the left, expand Libraries and then expand Documents.

8. Select Documents
9. If the WindowsPowerShell folder does not exist, click New folder. Type WindowsPowerShell for
the folder name, and press Enter.

10. Double-click the WindowsPowerShell folder.


11. In the File name text box, type Profile.ps1 and press Enter.

12. Close the ISE window.

13. Close all open console windows.


14. Open a new Windows PowerShell console using the Administrator account.

15. Verify that the prompt is C:\.

16. Run:

Get-Module

17. Verify that ActiveDirectory is listed.


12-8 Automating Administration with Windows PowerShell

Lesson 3
Working with Alternative Credentials
Contents:
Demonstration 9
Using Profiles and Advanced Windows PowerShell Techniques 12-9

Demonstration
Demonstration: Creating and Using a Credential

Demonstration Steps
1. Run:

$cred = Get-Credential --
-Credential ADATUM\Administrator

2. In the dialog box, type Pa$$w0rd and press Enter.

3. Run:

Invoke-Command ---Computername LON-DC1 ---scriptblock {Get-EventLog --


-LogName Security --
-
Newest 10}

4. Verify you receive a kerberos authentication error.

5. Run:

Invoke-Command ---Computername LON-DC1 ---scriptblock {Get-EventLog --


-LogName Security --
-
Newest 10} ---credential $cred

6. Verify the 10 newest entries from computer LON-DC1 are displayed.

7. Close the Windows PowerShell console window.


12-10 Automating Administration with Windows PowerShell

Module Review and Takeaways


Real-world Issues and Scenarios
Some administrators have their profile script load such a large number of add-ins and modules that
Windows PowerShell can take several minutes to start. Try to include only those add-ins or modules that
you absolutely need constantly. Also, remember that some add-ins and modules can conflict with one
another. If you experience strange behavior in the shell, try starting a new shell session by running
powershell.exe ---noprofile to suspend profile script execution. Then, load only one add-in or module at
a time to see which one caused the strange behavior.

Common Issues and Troubleshooting Tips


Common Issue Troubleshooting Tip

Profile script will not load and run. Make sure that you have put the script in
the correct location and given it the correct
file name. Also make sure that script
execution is enabled through the shell
execution policy.

Lab Review Questions and Answers


Question and Answers
Question: If your user profile is redirected to a network location, will profile scripts still work?

Answer: Yes. Wherever your Documents folder is located, just put the profile script in the appropriate
location within the Documents folder. An advantage to a redirected profile is that your profile script will
be available on any computer that you log on to.

Question: How can you quickly obtain a list of methods and properties for a string object or for a date
object?

Answer: Pipe a string or a date to the Get-Member command for a list of the object’s properties and
methods.

Вам также может понравиться