Sunteți pe pagina 1din 156

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

10961C
Automating Administration with Windows
PowerShell
Companion Content
ii 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.

© 2017 Microsoft Corporation. All rights reserved.


Microsoft and the trademarks listed at
https://www.microsoft.com/en-us/legal/intellectualproperty/Trademarks/Usage/General.aspx are
trademarks of the Microsoft group of companies. All other trademarks are property of their respective
owners

Product Number: 10961C

Released: 09/2017
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 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 Notices. The Licensed Content may include third party code tent that Microsoft, not the
third party, licenses to you under this agreement. Notices, if any, for the third party code ntent are included
for your information only.

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 technology, 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 technology,
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 July 2013


Getting started with Windows PowerShell 1-1

Module 1
Getting started with Windows PowerShell
Contents:
Lesson 1: Overview and background of Windows PowerShell 2

Lesson 2: Understanding command syntax 5


Lesson 3: Finding commands 8

Module Review and Takeaways 12

Lab Review Questions and Answers 13


1-2 Automating Administration with Windows PowerShell

Lesson 1
Overview and background of Windows PowerShell
Contents:
Question and Answers 3
Resources 3
Demonstration: Configuring the console 3
Demonstration: Configuring the ISE 4
Getting started with Windows PowerShell 1-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, if you are just running a few commands, the console is sufficient.

Resources

Windows PowerShell versions

Additional Reading: For more information about installing and configuring WMF 5.1, refer
to “Install and Configure WMF 5.1” at https://aka.ms/u33mya.
Additional Reading: For more information on the Windows Management Framework 5.1,
refer to “Microsoft Download Center” at https://aka.ms/i31ojp.

Configuring the console

Additional Reading: For a list of updates to the Windows Console in Windows Server
2016, refer to “What's New in the Windows Console in Windows Server 2016 Technical Preview”
at https://aka.ms/ebr7o4.

Demonstration: Configuring the console


Demonstration Steps
1. On LON-CL1, click Start, and then type powersh to display the Windows PowerShell icon. Right-click
Windows PowerShell, and then select Run as administrator.

2. When Windows PowerShell is running, right-click the icon on the taskbar, and then select Pin to
taskbar.

Note: Ensure that the window title bar reads Administrator and that it does not include
(x86).

3. Select 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 then select an appropriate font size (a font size of 20– 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 entire
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. Make sure that the horizontal scroll bar does not display at the bottom of the window.
Select OK.

7. To start a transcript of the Windows PowerShell session, type the following command in the console,
and then press Enter:

Start-Transcript C:\Day1.txt
1-4 Automating Administration with Windows PowerShell

8. Type the following command, and then press Enter:

Get-ChildItem

9. Select the output of the previous command, and then press Enter.

10. Click Start, type notepad, and then select the Notepad icon.
11. Paste the contents of the clipboard into the Notepad window.

12. Switch to Windows PowerShell.

13. Press the Up arrow key to display the command that you entered previously.
14. Close the Windows PowerShell window.

15. Open File Explorer, and then browse to and open C:\Day1.txt.

16. Close all open windows. Do not save changes in Notepad.

Demonstration: Configuring the ISE


Demonstration Steps
1. On LON-CL1, right-click the Windows PowerShell taskbar icon, and then select Run ISE as
Administrator.

2. On the ISE toolbar, select the Show Script Pane Right icon, select the Show Script Pane Maximized
icon, and then select Show Script Pane Top. Switch to single-pane view by selecting Show Script
Pane Maximized.

3. Use the blue arrow in the upper-right corner of the pane to show and hide the Script pane, toggling
between the script and console panes.
4. Select the Show Command Add-on and Show Command Window options to show and hide the
command add-on and the command window.
5. Use the slider in the lower-right corner of the window to adjust the font size in the console and the
Script pane.

6. On the Tools menu in the ISE, select Options. Select Manage Themes and then select a theme, such
as Presentation. Select OK to close the dialog boxes.
7. Close the Windows PowerShell ISE.
Getting started with Windows PowerShell 1-5

Lesson 2
Understanding command syntax
Contents:
Question and Answers 6
Demonstration: Viewing help 6
Demonstration: Using About files 7
1-6 Automating Administration with Windows PowerShell

Question and Answers


Question: How would you search for a cmdlet that retrieves the properties of a computer from Active
Directory?

Answer: You can use what you know about cmdlet name structures to help you guess the name
of the cmdlet. You know that Get retrieves resources so that you can work with their properties.
You also know that the nouns associated with Active Directory have the prefix AD. Based on this
information, you can use the Get-Help command and a wildcard value for the cmdlet name to
search for possible cmdlets by running the command Get-Help Get-AD*. Because you are
looking for the cmdlets that operate specifically on computers, you could even check if Get-Help
Get-ADComputer returns results.

Question: You wish to join multiple computers to the Adatum domain. The Add-Computer cmdlet’s -
ComputerName parameter accepts multiple values. Which of the following is a set of valid values for this
parameter?

( ) -ComputerName LON-CL2;LON-CL3;LON-CL4

( ) -ComputerName “LON-CL2, LON-CL3, LON-CL4”

( ) -ComputerName LON-CL2 LON-CL3 LON-CL4

( ) -ComputerName LON-CL2, -ComputerName LON-CL3 -ComputerName LON-CL4

( ) -ComputerName LON-CL2,LON-CL3,LON-CL4
Answer:

( ) -ComputerName LON-CL2;LON-CL3;LON-CL4
( ) -ComputerName “LON-CL2, LON-CL3, LON-CL4”

( ) -ComputerName LON-CL2 LON-CL3 LON-CL4

( ) -ComputerName LON-CL2, -ComputerName LON-CL3 -ComputerName LON-CL4


(√) -ComputerName LON-CL2,LON-CL3,LON-CL4
Feedback:

The correct way to pass multiple values to a parameter that accepts them is by separating them
with a comma and no spaces. In option 1, a semicolon is not a valid separator for parameter
values. In option 2, the entire string, including commas and spaces, will be passed as a single
value. In option 3, spaces are not a valid separator for parameter values. In option 4, you do not
pass multiple parameter values by specifying the parameter multiple times.

Demonstration: Viewing help


Demonstration Steps
1. On LON-CL1, on the task bar, click the Windows PowerShell icon.

2. In the Windows PowerShell console, type the following text, and then press Enter:

help Get-ChildItem

3. Discuss the basic help information for the Get-ChildItem command. Point out the –Recurse switch.
4. In the Windows PowerShell console, type the following text, and then press Enter:

Get-Help Get-ChildItem

5. Point out the difference between this output and the paged output of help.
Getting started with Windows PowerShell 1-7

Note: You might need to reduce the size of the console window to demonstrate the
paging of the output. If the console window is full screen, the command might display the output
in the single screen because it fits. As a result, there will be no paging. The content is otherwise
the same.

6. To display the floating window help, in the Windows PowerShell console, type the following text, and
then press Enter:

Get-Help Get-ChildItem –showwindow

7. To display the usage examples as part of the help output, in the Windows PowerShell console, type
the following text, and then press Enter:

Get-Help Get-ChildItem –Example

8. If you have an appropriate host computer or virtual machine that has Internet access (as mentioned
in the preparation steps), you can display the online help by typing the following text in the Windows
PowerShell console, and then pressing Enter:

Get-Help Get-ChildItem –Online

Demonstration: Using About files


Demonstration Steps
1. In the Windows PowerShell console, type the following command, and then press Enter:

Get-Help about*

2. Type the following text, and then press Enter:

Get-Help about_aliases

3. Type the following text, and then press Enter:

Get-Help about_eventlogs -ShowWindow

4. Type the following text, and then press Enter:

Get-Help *beep*
1-8 Automating Administration with Windows PowerShell

Lesson 3
Finding commands
Contents:
Question and Answers 9
Resources 9
Demonstration: Viewing modules 9
Demonstration: Searching for cmdlets 10
Demonstration: Using aliases 10
Getting started with Windows PowerShell 1-9

Question and Answers


Question: What is the difference between Get-Help and Get-Command? Why might they return
different results for the same query?

Answer: Get-Help searches for help topics. Get-Command searches for commands. There
should be a help topic for every cmdlet, but no one enforces this. As a result, Get-Help might not
return anything for an existing command that does not have a help topic.

Additionally, when no results return when querying a command name, Get-Help will perform a
full-text search of the help files by using the same query value. Get-Command has no such
capability, and as a result, Get-Help might return results when Get-Command does not.

Resources

Finding cmdlets

Additional Reading: For more information on Windows PowerShell, refer to “PowerShell


Gallery” at https://aka.ms/iast9g.

Demonstration: Viewing modules


Demonstration Steps
1. On LON-DC1, right-click Start and then click Windows PowerShell (Admin).

2. In the Windows PowerShell console, type the following command, and then press Enter:

Get-Module

Note: There are currently only two modules loaded.

3. In the Windows PowerShell console, type the following command, and then press Enter:

Get-ADUser Lara

4. In the Windows PowerShell console, type the following command, and then press Enter:

Get-Module

Note: Now the ActiveDirectory module is loaded.

5. In the Windows PowerShell console, type the following command, and then press Enter:

Get-Module -ListAvailable

6. Scroll through the results, noting that all these modules are loaded or are available to load.

7. In the Windows PowerShell console, type the following command, and then press Enter:

Import-Module ServerManager

8. In the Windows PowerShell console, type the following command, and then press Enter:
1-10 Automating Administration with Windows PowerShell

Get-Module

Note: Now the ServerManager module is loaded.

Demonstration: Searching for cmdlets


Demonstration Steps
1. On your host computer, open Microsoft Edge.

2. In the address bar, type enable network adapter with powershell, and then press Enter.

3. One of the top results should be the TechNet topic for Enable-NetAdapter. Open the topic and
review it with the class.

4. Go to http://www.powershellgallery.com.

5. In the Search Items box, type dns configuration, and then press Enter.

6. On the Items page, under Categories, select Cmdlet.


7. Review the results with the class.

8. On LON-CL1, in the Windows PowerShell console, type the following command, and then press
Enter:

Get-Command *net*

Note: The results also include applications found in the Windows system folder that have
net in the name.

9. In the Windows PowerShell console, type the following command, and then press Enter:

Get-Help *net* -Category cmdlet

10. Review the results with the class, noting the effect of the -Category parameter.

Demonstration: Using aliases


Demonstration Steps
1. On LON-CL1, in the Windows PowerShell console, type the following command, and then press
Enter:

dir

2. Type the following command, and then press Enter:

Get-ChildItem

Note: The results of these two commands are the same.

3. Type the following command, and then press Enter:

Get-Alias dir
Getting started with Windows PowerShell 1-11

Note: The definition for dir is Get-ChildItem.

4. Type the following command, and then press Enter:

New-Alias list Get-ChildItem

5. Type the following command, and then press Enter:

list

Note: The results are the same as they are for dir and Get-ChildItem.

6. Type the following command, and then press Enter:

Get-Alias -Definition Get-ChildItem

Note: The results include both dir and list, along with others.
1-12 Automating Administration with Windows PowerShell

Module Review and Takeaways


Best Practices
• When you discover a new command, either by using Get-Help or Get-Command, or by reading
about the command somewhere, always read the command’s help file and learn about its additional
capabilities.
• Even familiar commands can gain new functionality in new versions of Windows PowerShell. Read the
help files even of commands that you already know well from earlier versions, to see what new
features might exist.

Review Question
Question: What functionality does the ISE in Windows PowerShell 5.0 now have that was previously only
available in the console?

Answer: Windows PowerShell 5.0 now supports the Start-Transcript and Stop-Transcript
cmdlets. Support for these cmdlets was the most obvious difference between the ISE and the
console in previous versions.

Common Issues and Troubleshooting Tips


Common Issue Troubleshooting Tip

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

Cannot use Update-Help with computers From an Internet-connected computer, use Save-
not connected to the Internet. Help to download help content to a shared folder or
removable storage. On the unconnected computer,
run Update-Help and then specify the shared folder
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 listed in
the PSModulePath environment variable, and only if
the module has the necessary metadata to tell
Update-Help where to find updated help files online.
Not all help might be available in all languages, and
Windows PowerShell will resort to en-US (US English)
help files if necessary.
Getting started with Windows PowerShell 1-13

Lab Review Questions and Answers


Lab A: Configuring Windows PowerShell
Question and Answers
Question: Why might you configure alternative text colors in the ISE?

Answer: Text and screen color are a matter of personal preference. However, some default ISE
colors can be difficult to see, such as the default light gray used for curly brackets and other
punctuation. Changing the colors can make these elements easier to see, helping you avoid
errors.

Question: What causes a horizontal scroll bar in the Windows PowerShell console window?

Answer: You will see a horizontal scroll bar when the screen buffer size is set to a value that is
greater than the window size.

Lab B: Finding and running basic commands

Question and Answers


Question: What are some methods for finding commands, other than using Get-Help and Get-
Command?

Answer: You can use the Get-Module command with the -ListAvailable parameter to search for
available modules. The results of the Get-Module command include a partial list of commands.
This can help you identify possible nouns, or you can use the module name as a parameter in
Get-Command.

You can use the Get-Alias command to identify the Windows PowerShell command that runs
behind the scenes when you run a command that you used in cmd.exe or Linux environments
and the command works in Windows PowerShell.
Cmdlets for administration 2-1

Module 2
Cmdlets for administration
Contents:
Lesson 1: Active Directory administration cmdlets 2

Lesson 2: Network configuration cmdlets 6


Lesson 3: Other server administration cmdlets 9

Module Review and Takeaways 11

Lab Review Questions and Answers 12


2-2 Automating Administration with Windows PowerShell

Lesson 1
Active Directory administration cmdlets
Contents:
Question and Answers 3
Demonstration: Managing users and groups 3
Demonstration: Managing Active Directory objects 4
Cmdlets for administration 2-3

Question and Answers


Question: Which of the following cmdlet verbs is not associated with the ADUser noun?

( ) Get
( ) Update

( ) New

( ) Remove
( ) Set

Answer:

( ) Get
(√) Update

( ) New

( ) Remove
( ) Set

Feedback:
The Update verb is not associated with the noun ADUser. There is no Update-ADUser cmdlet.
Question: The default value for the -ProtectedFromAccidentalDeletion parameter of New-
ADOrganizationalUnit is $true.

( ) True

( ) False

Answer:

(√) True
( ) False

Feedback:
The default value for -ProtectedFromAccidentalDeletion is $true.

Demonstration: Managing users and groups


Demonstration Steps
Create a new global group in the IT department
1. On LON-CL1, click Start and then type powersh.

2. In the search results, right-click Windows PowerShell, and then click Run as administrator.
3. In the Administrator: Windows PowerShell window, type the following command, and then press
Enter:

New-ADGroup -Name HelpDesk -Path "ou=IT,dc=Adatum,dc=com" –GroupScope Global

Create a new user in the IT department


• Type the following command, and then press Enter:

New-ADUser -Name “Jane Doe” -Department “IT”


2-4 Automating Administration with Windows PowerShell

Add two users from the IT department to the HelpDesk group


• In the Administrator: Windows PowerShell window, type the following command, and then press
Enter:

Add-ADGroupMember “HelpDesk” -Members “Lara”,”Jane Doe”

Note: The -Members parameter accepts a value that maps to several different properties.

Set the address for all HelpDesk group users


1. In the Administrator: Windows PowerShell window, type the following command, and then press
Enter:

Get-ADGroupMember HelpDesk

2. Type the following command, and then press Enter:

Set-ADUser Lara -StreetAddress "1530 Nowhere Ave." -City "Winnipeg" -State "Manitoba"
-Country "CA"

Verify the group membership for the new user


• In the Administrator: Windows PowerShell window, type the following command, and then press
Enter:

Get-ADPrincipalGroupMembership “Jane Doe”

Verify the updated user properties


• In the Administrator: Windows PowerShell window, type the following command, and then press
Enter:

Get-ADUser Lara -Properties StreetAddress,City,State,Country

Demonstration: Managing Active Directory objects


Demonstration Steps
Create an Active Directory contact object that has no dedicated cmdlets
• On LON-CL1, in the Administrator: Windows PowerShell window, type the following command,
and then press Enter:

New-ADObject -Name JohnSmithcontact -Type contact -DisplayName “John Smith


(Contoso.com)”

Verify the creation of the contact


• In the Administrator: Windows PowerShell window, type the following command, and then press
Enter:

Get-ADObject -Filter ‘ObjectClass -eq “contact”’


Cmdlets for administration 2-5

Manage user properties by using Active Directory object cmdlets


• In the Administrator: Windows PowerShell window, type the following command, and then press
Enter:

Set-ADObject -Identity “CN=Lara Raisic,OU=IT,DC=Adatum,DC=com" -Description “Member


of support team”

Verify the property changes


• In the Administrator: Windows PowerShell window, type the following command, and then press
Enter:

Get-ADUser Lara -Properties Description

Change the name of the HelpDesk group to SupportTeam


• In the Administrator: Windows PowerShell window, type the following command, and then press
Enter:

Rename-ADObject -Identity “CN=HelpDesk,OU=IT,DC=Adatum,DC=com” -NewName SupportTeam

Verify the HelpDesk group name change


• In the Administrator: Windows PowerShell window, type the following command, and then press
Enter:

Get-ADGroup HelpDesk

Note: Note that the Name and DistinguishedName properties changed, but not the
SAMAccountName property.
2-6 Automating Administration with Windows PowerShell

Lesson 2
Network configuration cmdlets
Contents:
Question and Answers 7
Demonstration: Configuring network settings 7
Cmdlets for administration 2-7

Question and Answers


Question: Which two parameters can you use with *-NetIPAddress cmdlets to identify a network
interface?

Answer: You can use -InterfaceAlias or -InterfaceIndex to identify a network interface when using
*-NetIPAddress cmdlets.

Demonstration: Configuring network settings


Demonstration Steps
Test the network connection to LON-DC1
• In the Administrator: Windows PowerShell window, type the following command, and then press
Enter:

Test-Connection LON-DC1

Note: Note the speed of the connection so that you can compare it to the speed after you
make changes.

View the network configuration for LON-CL1


• In the Administrator: Windows PowerShell window, type the following command, and then press
Enter:

Get-NetIPConfiguration

Note: Note the IP address, default gateway, and Domain Name System (DNS) server.

Change the client IP address


1. In the Administrator: Windows PowerShell window, type the following command, and then press
Enter:

New-NetIPAddress -InterfaceAlias Ethernet -IPAddress 172.16.0.30 -PrefixLength 16

2. In the Administrator: Windows PowerShell window, type the following command, and then press
Enter:

Remove-NetIPAddress -InterfaceAlias Ethernet -IPAddress 172.16.0.40

3. Type Y and press Enter for both confirmation prompts.

Change the DNS server for LON-CL1


• In the Administrator: Windows PowerShell window, type the following command, and then press
Enter:

Set-DnsClientServerAddress -InterfaceAlias Ethernet -ServerAddress 172.16.0.11


2-8 Automating Administration with Windows PowerShell

Change the default gateway for LON-CL1


1. In the Administrator: Windows PowerShell window, type the following command, and then press
Enter:

Remove-NetRoute -InterfaceAlias Ethernet -DestinationPrefix 0.0.0.0/0

2. Type Y and press Enter for both confirmation prompts.

3. In the Administrator: Windows PowerShell window, type the following command, and then press
Enter:

New-NetRoute -InterfaceAlias Ethernet -DestinationPrefix 0.0.0.0/0 -NextHop


172.16.0.2

Confirm the network configuration changes


• In the Administrator: Windows PowerShell window, type the following command, and then press
Enter:

Get-NetIPConfiguration

Test the effect of the changes


• In the Administrator: Windows PowerShell window, type the following command, and then press
Enter:

Test-Connection LON-DC1

Note: It now takes much longer to receive a response from LON-DC1.


Cmdlets for administration 2-9

Lesson 3
Other server administration cmdlets
Contents:
Question and Answers 10
2-10 Automating Administration with Windows PowerShell

Question and Answers


Question: What Windows feature must you install before you can use Hyper-V cmdlets?

Answer: Before you can use Hyper-V cmdlets, at a minimum, you must install the Hyper-V
management module part of the Hyper-V feature.
Cmdlets for administration 2-11

Module Review and Takeaways


Best Practice
Be sure to run the Update-Help command periodically so that you have the most up-to-date help for
Windows PowerShell commands.

Review Questions
Question: What command in the Windows PowerShell command-line interface can you use instead of
ping.exe?

Answer: Test-Connection provides the same functionality as ping.exe.

Question: Name at least two ways in which you can create an Active Directory Domain Services (AD DS)
user account by using Windows PowerShell.

Answer: You can create a user account by using either the New-ADUser or the New-ADObject
cmdlet.

Common Issues and Troubleshooting Tips


Common Issue Troubleshooting Tip

When I run the Get-Help command for a This means that only partial help is installed on your
cmdlet with the -Example parameter, I do not system. Run the Update-Help command or use the
see any examples. -Online parameter with Get-Help to force the
command to open web-based help in the browser.

I update the Windows PowerShell version on Verify that your current operating system supports
my system, but a new command does not the command. It is possible that the command
appear to do anything. depends on underlying changes to features.
2-12 Automating Administration with Windows PowerShell

Lab Review Questions and Answers


Lab: Windows administration
Question and Answers
Question: Are any other websites on the LON-SVR1 server?

Answer: Yes. A site named Default Web Site should be there. You can find the answer by
running the Get-Website command and viewing the output.
Working with the Windows PowerShell pipeline 3-1

Module 3
Working with the Windows PowerShell pipeline
Contents:
Lesson 1: Understanding the pipeline 2

Lesson 2: Selecting, sorting, and measuring objects 5


Lesson 3: Filtering objects out of the pipeline 9

Lesson 4: Enumerating objects in the pipeline 11

Lesson 5: Sending pipeline data as output 13


Module Review and Takeaways 16

Lab Review Questions and Answers 17


3-2 Automating Administration with Windows PowerShell

Lesson 1
Understanding the pipeline
Contents:
Question and Answers 3
Demonstration: Viewing object members 3
Demonstration: Formatting pipeline output 4
Working with the Windows PowerShell pipeline 3-3

Question and Answers


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

Answer: It depends on who wrote the command that produced the object. For most Microsoft
commands, the MSDN Library documents the output objects. Using the object’s type name in an
Internet search is frequently the fastest way to find existing documentation about an object.
Question: The Format-Wide cmdlet accepts the -AutoSize and -Wrap parameters.

( ) True

( ) False
Answer:

( ) True

(√) False

Feedback:

The Format-Wide cmdlet does not accept the -Wrap parameter.

Demonstration: Viewing object members


Demonstration Steps
1. On LON-CL1, click Start and then type powersh.
2. In the search results, right-click Windows PowerShell, and then click Run as administrator.

3. In the Administrator: Windows PowerShell window, type the following command, and then press
Enter:

Get-Service | Get-Member

4. In the Windows PowerShell console, type the following command, and then press Enter:

Get-Process | Get-Member

5. In the Windows PowerShell console, type the following command, and then press Enter:

Get-ChildItem | Get-Member

Note: Note the default value for the PSIsContainer property and for the other returned
members.

6. In the Windows PowerShell console, type the following command, and then press Enter:

Get-ADUser -Filter * | Get-Member

Note: Note the number of returned properties and their names.

7. In the Windows PowerShell console, type the following command, and then press Enter:

Get-ADUser -Filter * -Properties *| Get-Member


3-4 Automating Administration with Windows PowerShell

Note: Note the number of returned properties and their names. This time, many more
properties are returned.

Demonstration: Formatting pipeline output


Demonstration Steps
1. On LON-CL1, in the Administrator: Windows PowerShell window, type the following command,
and then press Enter:

Get-Service

2. In the console, type the following command, and then press Enter:

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

3. In the console, type the following command, and then press Enter:

Get-ADComputer -Filter * -Properties OperatingSystem

4. In the console, type the following command, and then press Enter:

Get-ADComputer -Filter * -Properties OperatingSystem | ft -Property Name,


OperatingSystem

5. In the console, type the following command, and then press Enter:

Get-ADUser -Filter *

6. In the console, type the following command, and then press Enter:

Get-ADUser -Filter * | fw -AutoSize


Working with the Windows PowerShell pipeline 3-5

Lesson 2
Selecting, sorting, and measuring objects
Contents:
Question and Answers 6
Demonstration: Sorting objects 6
Demonstration: Measuring objects 7
Demonstration: Selecting objects 7
Demonstration: Creating calculated properties 7
3-6 Automating Administration with Windows PowerShell

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 improve performance. Select-Object can tell the previous commands that it requires no
more data. Some commands can then stop processing, thereby reducing the total amount of
time it takes Windows PowerShell to complete the task.

Demonstration: Sorting objects


Demonstration Steps
1. On LON-CL1, in the Administrator: Windows PowerShell window, type the following command,
and then press Enter:

Get-Process

2. In the Administrator: Windows PowerShell window, type the following command, and then press
Enter:

Get-Process | Sort-Object –Property ID

3. In the console, type the following command, and then press Enter:

Get-Service | Sort-Object –Property Status

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

4. In the console, type the following command, and then press Enter:

Get-Service | Sort-Object –Property Status -Descending

5. In the console, type the following command, and then press Enter:

Get-EventLog –LogName Security –Newest 10

6. In the console, type the following command, and then press Enter:

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


Clear-EventLog

7. In the console, type the following command, and then press Enter:

Get-ADUser -Filter * | Sort-Object –Property SurName | fw -AutoSize

Note: Users are sorted by column, and not by row. Also, any users created in earlier
demonstrations appear at the beginning of the list, because no value was set for the SurName
property when they were created.
Working with the Windows PowerShell pipeline 3-7

Demonstration: Measuring objects


Demonstration Steps
1. On LON-CL1, in the Administrator: Windows PowerShell window, type the following command,
and then press Enter:

Get-Service | Measure-Object

2. In the console, type the following command, and then press Enter:

Get-ADUser -Filter * | Measure-Object

3. In the console, type the following command, and then press Enter:

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

Demonstration: Selecting objects


Demonstration Steps
1. On LON-CL1, in the console, type the following command, and then press Enter:

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

2. In the console, type the following command, and then press Enter:

Get-Date | Select-Object –Property DayOfWeek

3. In the console, type the following command, and then press Enter:

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


EventID,TimeWritten,Message

4. In the console, type the following command, and then press Enter:

Get-ADComputer –Filter * -Properties OperatingSystem | Sort -Property OperatingSystem


| Select-Object -Property OperatingSystem,Name | fl -GroupBy OperatingSystem -
Property Name

Demonstration: Creating calculated properties


Demonstration Steps
1. On LON-CL1, in the console, type the following command, and then press Enter:

Get-ADUser -Filter * -Properties whenCreated

2. In the console, type the following command, and then press Enter:

Get-ADUser -Filter * -Properties whenCreated | Sort-Object -Property whenCreated -


Descending

3. In the console, type the following command, and then press Enter:

Get-ADUser -Filter * -Properties whenCreated | Sort-Object -Property whenCreated -


Descending | Select-Object -Property Name,@{n='Account age (days)';e={(New-TimeSpan -
Start $PSItem.whenCreated).Days}}
3-8 Automating Administration with Windows PowerShell

4. In the console, type the following command, and then press Enter:

Get-ADUser -Filter * -Properties whenCreated | Sort-Object -Property whenCreated -


Descending | Select-Object -Property Name,@{n='Account age (days)';e={(New-TimeSpan -
Start $PSItem.whenCreated).Days}}
Working with the Windows PowerShell pipeline 3-9

Lesson 3
Filtering objects out of the pipeline
Contents:
Question and Answers 10
Demonstration: Filtering 10
3-10 Automating Administration with Windows PowerShell

Question and Answers


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

Answer: This is obviously a personal opinion. The $PSItem variable is new in Windows
PowerShell 3.0, so experienced users frequently use $_ out of habit. The $_ variable is obviously
shorter and easier to type, but for many beginners, it is more visually 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 the Windows PowerShell own help files still use $_.

Question: Is the following command the most efficient way to produce a list of services that have names
beginning with svc?

Get-Service | Where Name –like svc*

Answer: No. The following command offers a better approach:

Get-Service –Name svc*

In this case, it filters the names as part of the Get-Service command.

Demonstration: Filtering
Demonstration Steps
1. On LON-CL1, in the console, type the following command, and then press Enter:

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

2. In the console, type the following command, and then press Enter:

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


| Select-Object -Property FriendlyName,OperationalStatus

3. In the console, type the following command, and then press Enter:

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


| Select-Object -Property FriendlyName,OperationalStatus
DriveLetter,FileSystemLabel,DriveType,FileSystem | fl

4. In the console, type the following command, and then press Enter:

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


Working with the Windows PowerShell pipeline 3-11

Lesson 4
Enumerating objects in the pipeline
Contents:
Question and Answers 12
Demonstration: Basic enumeration 12
Demonstration: Advanced enumeration 12
3-12 Automating Administration with Windows PowerShell

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 the enumeration programming constructs that
many programming and scripting languages have. 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: Basic enumeration


Demonstration Steps
1. In the console, type the following command, and then press Enter:

Get-Service | ForEach Name

2. In the console, type the following command, and then press Enter:

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

Demonstration: Advanced enumeration


Demonstration Steps
1. In the console, type the following command, and then press Enter:

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


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

2. In the console, type the following command, and then press Enter:

Get-ChildItem E:\ -Directory -Recurse | Where Name -eq Democode | ForEach-Object


{$PSItem.CreateSubdirectory('Test')} | Select-Object FullName
Working with the Windows PowerShell pipeline 3-13

Lesson 5
Sending pipeline data as output
Contents:
Question and Answers 14
Demonstration: Exporting data 14
3-14 Automating Administration with Windows PowerShell

Question and Answers


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

Answer: Many formats exist. The .xls and the .xlsx formats are common requests, although
Windows PowerShell does not contain a native command for reading or writing those formats.

Demonstration: Exporting data


Demonstration Steps
1. In the console, type the following command, and then press Enter:

Get-Process | ConvertTo-Html

Note: Because you used the verb ConvertTo, the data remains in Windows PowerShell and
displays on the screen.

2. In the console, type the following command, and then press Enter:

Get-Process | ConvertTo-Html | Out-File E:\Procs.html

Note: You must use this two-step approach, because Windows PowerShell does not
provide an Export-Html command.

3. Open File Explorer, navigate to E:\ , and then open the Procs.html file in Internet Explorer.
4. In the console, type the following command, and then press Enter:

Get-Process | ConvertTo-Json > E:\Procs.json

5. In File Explorer, navigate to E:\ , and then open the Procs.json file in Notepad.

6. In the console, type one of the following commands, and then press Enter:

Get-Service | ConvertTo-Csv | Out-File E:\Serv.csv


Get-Service | Export-Csv E:\Serv.csv

Note: Both commands have the same result.

7. In the console, type the following command, and then press Enter:

Notepad E:\Serv.csv

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

8. In the console, type the following command, and then press Enter:

Get-Service | Export-Clixml E:\Serv.xml


Working with the Windows PowerShell pipeline 3-15

9. In the console, type the following command, and then press Enter:

Notepad E:\Serv.xml

Note: Notice how properties with multiple values are represented.


3-16 Automating Administration with Windows PowerShell

Module Review and Takeaways


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

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

Answer: Both are functionally the same. Windows PowerShell 3.0 introduced $PSItem as an
easier-to-read alternative to $_, so $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 (such as in online articles or blogs) written by other
people for earlier versions, so you should remember both $_ and $PSItem.

Real-world Issues and Scenarios


One potentially challenging aspect of Windows PowerShell is that you can frequently achieve the same
result in several ways. Different people select different techniques based on their experiences, 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 or newer, the preceding 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, be aware that just one correct way to use Windows PowerShell
does not exist. Part of using Windows PowerShell is being able to understand many approaches,
arrangements of syntax, and techniques.

Common Issues and Troubleshooting Tips


Common Issue Troubleshooting Tip

The $_ variable does not work. The $_ variable is a special placeholder and works
only in positions where Windows PowerShell 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.

The variable name $_ is confusing to read. You can use the $PSItem variable instead. This
variable was introduced in Windows PowerShell 3.0.
You can use $PSItem in the same positions as $_.
Working with the Windows PowerShell pipeline 3-17

Lab Review Questions and Answers


Lab A: Using the pipeline
Question and Answers
Question: Suppose that you want to produce output that includes all of an object’s properties except
one. What is the most efficient way to do that?

Answer: The Select-Object command has an -ExcludeProperty parameter. Use it to list the one
property that you do not want to include, and use -Property * to include the remaining
properties.

Question: List the basic formatting commands, and explain why you might use each one.

Answer: Format-List allows you to view many properties for an object at one time. The
command truncates the property list when you also use Format-Table.

Format-Table creates output in a compact format that makes it is easier to view more than one
property for multiple objects. It also makes it possible to compare values among properties.
Format-Wide allows you to view many instances of a single property, like names, in as compact
a format as possible.

Lab B: Filtering objects

Question and Answers


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

Answer: Answers will vary. However, remember that you will probably encounter both forms of
the syntax as you discover examples, such as those in books or blogs, written by other Windows
PowerShell users.

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 Structured Query Language, it might help to remember
that the SELECT keyword chooses columns, and the WHERE keyword chooses rows. The
Windows PowerShell commands have similar names 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
have been inefficient and incorrect in this scenario.
3-18 Automating Administration with Windows PowerShell

Lab C: Enumerating objects

Question and Answers


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

Answer: Answers will vary. However, remember that you will probably encounter both forms of
the syntax as you discover examples, such as in books or blogs, that other Windows PowerShell
users have written.

Lab D: Sending output to a file


Question and Answers
Question: Can you use ConvertTo-Csv or Export-Csv to create a file delimited by a character other than
a comma? For example, can you create a tab-delimited file?

Answer: Yes. Both commands have a -Delimiter parameter that changes the delimiter used for
the file. Use "`t" to specify a tab character, and note that the quotation marks (" ") are required.

Question: The HTML data 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 Cascading Style Sheets (CSS). Does
the command offer a way to attach a style sheet?

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.
Understanding how the pipeline works 4-1

Module 4
Understanding how the pipeline works
Contents:
Lesson 1: Passing pipeline data 2

Lesson 2: Advanced techniques for passing pipeline data 5


Module Review and Takeaways 9

Lab Review Questions and Answers 10


4-2 Automating Administration with Windows PowerShell

Lesson 1
Passing pipeline data
Contents:
Question and Answers 3
Demonstration: Passing data by using ByValue 3
Demonstration: Passing data ByPropertyName 3
Understanding how the pipeline works 4-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 work with any kind of input. Therefore, each of
them defines a parameter named –InputObject. That parameter receives 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: Passing data by using ByValue


Demonstration Steps
1. On LON-CL1, click Start, and then type powershell.

2. In the search results, right-click Windows PowerShell ISE, and then select Run as administrator.
3. In the Administrator: Windows PowerShell ISE window, type the following command, and then
press Enter:

Get-Service –Name BITS | Stop-Service

Show the Script pane on top of the Console pane.


4. In the console, type the following command, and then press Enter:

Get-Service | Get-Member

Show that TypeName is ServiceController.


5. In the console, type the following command, and then press Enter:

Get-Help Stop-Service –ShowWindow

6. In the Help window, show that the –InputObject parameter accepts objects of the type
ServiceController from the pipeline by using ByValue.
You should have determined that the objects that the first command, Get-Service, produced will
attach to the –InputObject parameter of the second command, Stop-Service.

7. Close the Help window.

8. Close the Windows PowerShell ISE window.

Demonstration: Passing data ByPropertyName


Demonstration Steps
1. On LON-CL1, click Start, and then type powersh.

2. In the search results, right-click Windows PowerShell on the taskbar, and then select Run as
administrator.
3. In the Administrator: Windows PowerShell window, type the following command, and then press
Enter:

Get-ADComputer LON-DC1 | Get-Process

Point out the “Cannot validate argument on parameter ‘ComputerName’” error. This means that the
object that Get-ADComputer returns does not have a ComputerName property and no other
property name matches a parameter name that accepts pipeline input.
4-4 Automating Administration with Windows PowerShell

4. In the console window, type the following command, and then press Enter:

Get-ADComputer LON-DC1 | Get-Member

Point out the members of Get-ADComputer and focus on the Name property.

5. In the console window, type the following command, and then press Enter:

Get-Help Get-Process –ShowWindow

Review the parameters and focus on the parameters that accept either ByValue or ByPropertyName
pipeline input and that two of them accept ByPropertyName values. Call out the ComputerName
parameter that maps to the Name property of Get-ADComputer.

6. In the console window, type the following command, and then press Enter:

Get-ADComputer LON-DC1 | Select-Object @{n='ComputerName';e={$PSItem.Name}} | Get-


Process

Remind students that they learned how to create a calculated value in Module 3, “Working with the
Windows PowerShell pipeline .” Reinforce that $PSItem is a special variable that represents the object
that pipes to Select-Object.
Understanding how the pipeline works 4-5

Lesson 2
Advanced techniques for passing pipeline data
Contents:
Question and Answers 6
Demonstration: Overriding the pipeline 6
Demonstration: Using parenthetical commands 6
Demonstration: Expanding property values 7
4-6 Automating Administration with Windows PowerShell

Question and Answers


Question: What are some reasons you would use parenthetical commands instead of the pipeline?

Answer: Several answers are possible. Some of them include:


• Use parenthetical commands when the output of the command that you want to use as
input for another command does not match the required data type.

• In some cases, a parenthetical command can be more efficient than the piped command. For
example, if a parameter can take multiple values as input, it is faster to pass those with a
parenthetical command than it is to pipe that input into the command individually.

• You can use parenthetical commands to pass data to parameters that do not normally take
piped input.

Demonstration: Overriding the pipeline


Demonstration Steps
1. On LON-CL1, click Start, and then type powersh.
2. In the search results, right-click Windows PowerShell on the taskbar, and then select Run as
administrator.

3. Click Start, type Notepad, and then open the Notepad app.
4. In the Administrator: Windows PowerShell window, type the following command, and then press
Enter:

Get-Process -Name Notepad | Stop-Process

This command runs without error.


5. Click Start, and then click Notepad.

6. In the console, type the following command, and then press Enter:

Get-Process -Name Notepad | Stop-Process –Name Notepad

This command generates an error.

7. Review the error, and then discuss how using the –Name parameter causes an error.

Demonstration: Using parenthetical commands


Demonstration Steps
1. On LON-CL1, in the Administrator: Windows PowerShell window, type the following command,
and then press Enter:

New-ADGroup “London Users” -GroupScope global

2. In the console, type the following command, and then press Enter:

Get-ADGroup "London Users" | Add-ADGroupMember

Note that a prompt to enter users appears. Press Enter. You will see an error because no member was
specified.
Understanding how the pipeline works 4-7

3. In the console, type the following command, and then press Enter:

Get-ADGroup "London Users" | Add-ADGroupMember -Members (Get-ADUser -Filter {City -eq


'London'})

4. In the console, type the following command, and then press Enter:

Get-ADGroupMember “London Users”

Note: Note the users added to the London Users group.

Demonstration: Expanding property values


Demonstration Steps
1. On LON-CL1, click Start, and then type powershell.
2. In the search results, right-click Windows PowerShell ISE, and then select Run as administrator.

3. In the Administrator: Windows PowerShell ISE window, type the following command in Windows
PowerShell ISE:

Get-ADComputer –Filter *

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

4. In the Script pane, type the following command, and then press Enter:

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

This will return an error. Explain that your goal is to display a list of services that are running on every
computer in the domain.

5. In the Console pane, type the following command, and then press Enter:

Get-ADComputer –Filter * | Get-Member

Explain that the command produces objects of the type ADComputer, as shown by the output of
Get-Member.

6. In the Console pane, type the following command, and then press Enter:

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

7. In the Console pane, type the following command, and then press Enter:

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.
4-8 Automating Administration with Windows PowerShell

8. In the Console pane, type the following command, and then press Enter:

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. In the Console pane, run the following command, and then press Enter:

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

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

9. In the Console pane, type the following command, and then press Enter:

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 the following command:

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

The total command should look like this:

Get-Service –ComputerName (Get-ADComputer –Filter * | Select-Object –ExpandProperty


Name)

11. Press F5 to run the command. As per your original goal that was outlined in step 3, it should display a
list of services from every computer in the domain. You might see errors if every computer is not
online or available. However, the command will try to contact each one.
Understanding how the pipeline works 4-9

Module Review and Takeaways


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

Review Question
Question: Because Windows PowerShell handles pipeline input binding invisibly, 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 attaches to each parameter. Read the Help file, especially the
examples, for this command to learn more details.

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 to submit a
request to the command author to support pipeline input in a future release.
4-10 Automating Administration with Windows PowerShell

Lab Review Questions and Answers


Lab: Working with pipeline parameter binding
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.

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.


Using PSProviders and PSDrives 5-1

Module 5
Using PSProviders and PSDrives
Contents:
Lesson 1: Using PSProviders 2

Lesson 2: Using PSDrives 4


Module Review and Takeaways 7

Lab Review Questions and Answers 8


5-2 Automating Administration with Windows PowerShell

Lesson 1
Using PSProviders
Contents:
Question and Answers 3
Demonstration: Viewing PSProvider help 3
Using PSProviders and PSDrives 5-3

Question and Answers


Question: What other kinds of PSProviders might exist as add-ins in the Windows PowerShell command-
line interface?

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

Demonstration: Viewing PSProvider help


Demonstration Steps
1. On LON-CL1, click Start and then type powersh.

2. In the results list, right-click Windows PowerShell and then click Run as administrator.
3. In the Windows PowerShell console, type the following command, and then press Enter:

Get-PSProvider

4. In the console, type the following command, and then press Enter:

Import-Module ActiveDirectory

5. In the console, type the following command, and then press Enter:

Get-PSProvider

6. In the console, type the following command, and then press Enter:

Get-Help Registry
5-4 Automating Administration with Windows PowerShell

Lesson 2
Using PSDrives
Contents:
Question and Answers 5
Demonstration: Managing the file system 5
Demonstration: Managing the registry 5
Using PSProviders and PSDrives 5-5

Question and Answers


Question: What are dynamic parameters and how do they relate to PSProviders?

Answer: Dynamic parameters are parameters that are available only under certain conditions.
PSProviders sometimes define dynamic parameters for certain cmdlets to help manage the
underlying technology.

Demonstration: Managing the file system


Demonstration Steps
1. ON LON-CL1, in the PowerShell console, type the following command, and then press Enter:

Cd C:\

2. In the console, type the following command, and then press Enter:

Set-Location C:\Windows

3. In the console, type the following command, and then press Enter:

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

4. In the console, type the following command, and then press Enter:

Dir WINDIR:

5. In the console, type the following command, and then press Enter:

Get-ChildItem WINDIR:

6. In the console, type the following command, and then press Enter:

New-Item E:\Mod05\Temp -ItemType Directory

Demonstration: Managing the registry


Demonstration Steps
1. In the Windows PowerShell console, type the following command, and then press Enter:

Set-Location HKLM:\Software

2. In the console, type the following command, and then press Enter:

Get-ChildItem

3. In the console, type the following command, and then press Enter:

New-Item -Name Demo

4. In the console, type the following command, and then press Enter:

New-ItemProperty -Path HKLM:\Software\Demo -Name Demo -Value Test -PropertyType


String
5-6 Automating Administration with Windows PowerShell

5. In the console, type the following command, and then press Enter:

Get-ItemProperty -Path Demo


Using PSProviders and PSDrives 5-7

Module Review and Takeaways


Review Question
Question: What is the advantage of managing a data store such as Active Directory by using a
PSProvider instead of commands?

Answer: A PSProvider can be dynamic. When a technology is dynamically extended, a


PSProvider offers a good way to expose that technology when you do not know the commands
in advance. For example, you can extend IIS by using add-ins. You cannot know in advance what
add-ins will be available or loaded, and so you cannot create commands for all of them. 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 the Get-ChildItem cmdlet 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 it occurs because
each PSProvider has different capabilities. The Registry provider does not support the –Filter parameter.

Common Issues and Troubleshooting Tips


Common Issue Troubleshooting Tip

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

Lab Review Questions and Answers


Lab: Using PSProviders and PSDrives
Question and Answers
Question: Of the PSProviders that are 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, which is indicated by the Credentials capability. Load
the ActiveDirectory module to see that the ActiveDirectory provider supports alternative
credentials.
Question: Windows PowerShell 3.0 and newer 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 File
Explorer. This works correctly only when the drive name is a single letter and is mapped to a
FileSystem location.
Querying management information by using CIM and WMI 6-1

Module 6
Querying management information by using CIM and WMI
Contents:
Lesson 1: Understanding CIM and WMI 2

Lesson 2: Querying data by using CIM and WMI 4


Lesson 3: Making changes by using CIM and WMI 7

Module Review and Takeaways 10

Lab Review Questions and Answers 11


6-2 Automating Administration with Windows PowerShell

Lesson 1
Understanding CIM and WMI
Contents:
Question and Answers 3
Resources 3
Demonstration: Finding documentation for classes 3
Querying management information by using CIM and WMI 6-3

Question and Answers


Question: Can you think of any situations for which you have to use WMI instead of CIM?

Answer: The only situation occurs when you have to query a remote computer and you do not
want to create a CIM session that uses the DCOM protocol.

Resources
Architecture and technologies

Reference Links: You can access the DMTF website at www.dmtf.org.

Demonstration: Finding documentation for classes


Demonstration Steps
1. On the host computer, in a web browser, go to the Bing website (or use your preferred Internet
search engine). In the Search box, type Win32_BIOS.

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

3. Explain that this Microsoft Developer Network (MSDN) webpage is the documentation page for the
class. Review some of the class properties.
6-4 Automating Administration with Windows PowerShell

Lesson 2
Querying data by using CIM and WMI
Contents:
Question and Answers 5
Resources 5
Demonstration: Listing local repository namespaces by using WMI 5
Demonstration: Listing and sorting the classes from a namespace 5
Demonstration: Querying class instances 6
Demonstration: Using CIMSession objects 6
Querying management information by using CIM and WMI 6-5

Question and Answers


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

Answer: If you query a computer multiple times in a short period of time, a CIM session offers
much better performance than an ad-hoc connection.

Resources
Listing classes

Reference Links: A graphical WMI Explorer tool, written in a Windows PowerShell script, is
available at https://aka.ms/cu41zp. This tool can make it easier to explore the WMI classes that
are available on a particular computer.

Demonstration: Listing local repository namespaces by using WMI


Demonstration Steps
1. On LON-CL1, open the Windows PowerShell console as an administrator.

2. In the Windows PowerShell console, type the following command, and then press Enter:

Get-WmiObject –Namespace root –List -Recurse | Select -Unique __NAMESPACE

3. Note the root\CIMV2 namespace and the root\SecurityCenter2 namespace. You will use these in
the next demonstration.

Demonstration: Listing and sorting the classes from a namespace


Demonstration Steps
1. In the Windows PowerShell console, type the following command, and then press Enter:

Get-CimClass –Namespace root\SecurityCenter2

2. Observe the values returned. Point out the CimClassName, CimClassMethods, and
CimClassProperties column names and the values returned in each row.

3. In the Windows PowerShell console, type the following command, and then press Enter:

Get-CimClass –Namespace root\CIMv2

Explain that the class names starting with two underscores (__) are system classes. You can typically
ignore system classes.

4. In the Windows PowerShell console, type the following command, and then press Enter:

Get-CimClass –Namespace root\CIMv2 | Sort CimClassName

Explain that an alphabetical list is 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.
6-6 Automating Administration with Windows PowerShell

5. To find all the classes in the root\CIMv2 namespace that have network in the class name, type the
following command in the Windows PowerShell console, and then press Enter:

Get-CimClass *network* | Sort CimClassName

Note that this technique cannot search class descriptions, because that information is not stored in
the repository.

Demonstration: Querying class instances


Demonstration Steps
1. In the Windows PowerShell console, type the following command, and then press Enter:

Get-WmiObject –Class Win32_Service

2. In the Windows PowerShell console, type the following command, and then press Enter:

Get-CimInstance –ClassName Win32_Process

3. In the Windows PowerShell console, type the following command, and then press Enter:

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

4. In the Windows PowerShell console, type the following command, and then press Enter:

Get-CimInstance –Query “SELECT * FROM Win32_NetworkAdapter"

Demonstration: Using CIMSession objects


Demonstration Steps
1. In the Windows PowerShell console, type the following command, and then press Enter:

$s = New-CimSession –ComputerName LON-DC1

2. In the Windows PowerShell console, type the following command, and then press Enter:

Get-CimInstance –CimSession $s –ClassName Win32_OperatingSystem

3. In the Windows PowerShell console, type the following command, and then press Enter:

$s | Remove-CimSession
Querying management information by using CIM and WMI 6-7

Lesson 3
Making changes by using CIM and WMI
Contents:
Question and Answers 8
Demonstration: Finding methods and documentation 8
Demonstration: Invoking methods of repository objects 9
6-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 the -WhatIf or the -Confirm parameter. When you use
this command to invoke a method, the method will run, but you will not have any way to test
your command.

Demonstration: Finding methods and documentation


Demonstration Steps
1. On LON-CL1, in the Windows PowerShell console, type the following command, and then press
Enter:

Get-WmiObject –ClassName Win32_Service | Get-Member

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


2. In the Windows PowerShell console, type the following command, and then press Enter:

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


List Name,Definition

3. Try the same thing by using CIM. In the Windows PowerShell console, type the following command,
and then press Enter:

Get-CimClass –Class Win32_Service | Select-Object –ExpandProperty CimClassMethods |


Sort-Object -Property Name

Note that although you get all the methods, the information is not as detailed as what you get from
Get-WmiObject.

4. Use the preceding Get-CimClass command, but pipe the results to Get-Member. In the Windows
PowerShell console, type the following command, and then press Enter:

Get-CimClass –Class Win32_Service | Get-Member

Note that this does not return the methods that the previous CIM and WMI commands did, but it
returns five additional methods. These methods are from the
Microsoft.Management.Infrastructure.CimClass namespace and not from Win32_Service.

5. In a web browser on the host computer, go to the Bing website (or your preferred search engine).

6. Type Win32_Service as the search term.

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

The MSDN documentation page at https://aka.ms/rpsria should

8. On the webpage, scroll down to the “Methods” section, and then click Change.
appear.

Explain that this method has 11 parameters. Review the parameters with the class.
Querying management information by using CIM and WMI 6-9

Demonstration: Invoking methods of repository objects


Demonstration Steps
1. On LON-CL1, in the Windows PowerShell console, type the following command, and then press
Enter:

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


Reboot

2. On the taskbar, in the Search box, type Paint, click the Paint icon in the returned list, and then verify
that the Paint application opens.

3. In the Windows PowerShell console or Windows PowerShell ISE, type the following command, and
then press Enter:

Get-CimInstance –Class Win32_Process –Filter "Name='mspaint.exe'" | Invoke-CimMethod


–Name Terminate

4. Ensure that Paint closes.


6-10 Automating Administration with Windows PowerShell

Module Review and Takeaways


Best Practice
Use CIM commands whenever possible. Compared to WMI commands, CIM commands offer better
performance, and Microsoft continues to develop and improve the CIM commands over time.

Review Question
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 might 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


Most organizations have deployed Windows Management Framework 3.0 or newer. This means that you
should use the CIM commands for ad-hoc connections in all environments. Microsoft is encouraging the
use of CIM over WMI whenever possible.

Tools
Tool Description Where to find it

PowerShell Scriptomatic A graphical tool for exploring the https://aka.ms/flb9y0


repository

A WMI Explorer tool A tool that provides the ability to https://aka.ms/kfxmrj


browse and view WMI namespaces,
classes, instances, and properties in a
single pane of view

Common Issues and Troubleshooting Tips


Common Issue Troubleshooting Tip

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

You get errors when you use CIM to WS-MAN has specific requirements for connectivity
connect to a remote computer by using the that include mutual authentication. Between trusted
WS-MAN protocol. computers in a domain, mutual authentication is
automatic. Outside a domain, additional configuration
is required. Module 10, “Administering remote
computers,” provides more details about the
additional configuration steps.

You get an access denied error when Only the members of a computer’s local
attempting to connect to a remote Administrators group can remotely query information
computer. from that computer. You need to either open
Windows PowerShell by using an appropriate
administrator user account or provide an alternative
credential when querying.
Querying management information by using CIM and WMI 6-11

Lab Review Questions and Answers


Lab: Working with CIM and WMI
Question and Answers
Question: One of your lab tasks directed you to query Win32_Product. Do you know of any
disadvantages of using this class?

Answer: The class forces Windows Installer to revalidate all installed packages. On computers
that have many installed packages, the validation process might take a long time to complete
and might 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 each one uses to communicate with remote
computers. WMI uses an earlier implementation of the Distributed Management Task Force
(DMTF) repository, whereas CIM is fully compliant with the current DMTF standard.
Working with variables, arrays, and hash tables 7-1

Module 7
Working with variables, arrays, and hash tables
Contents:
Lesson 1: Using variables 2

Lesson 2: Manipulating variables 6


Lesson 3: Manipulating arrays and hash tables 10

Module Review and Takeaways 14

Lab Review Questions and Answers 15


7-2 Automating Administration with Windows PowerShell

Lesson 1
Using variables
Contents:
Question and Answers 3
Demonstration: Assigning a variable type 3
Working with variables, arrays, and hash tables 7-3

Question and Answers


Question: Why is it sometimes necessary to assign a variable type?

Answer: You need to assign a variable type when Windows PowerShell cannot accurately
determine the correct variable type. One common issue is non-string data that is enclosed in
quotes. Any text enclosed in quotes is interpreted as a string by default. If you want the text in
quotes to be interpreted as another variable type such as DateTime, then you need to specify the
variable type.

Demonstration: Assigning a variable type


Demonstration Steps
1. On LON-CL1, click the Start button, and then type powersh.

2. In the results list, right-click Windows PowerShell and then click Run as administrator.
3. To set the value of $num1 to 5, at the Windows PowerShell prompt, type the following command,
and then press Enter:

$num1 = 5

4. To display the value of $num1, type the following command, and then press Enter:

$num1

5. To set the value of $logFile to be C:\Logs\Log.txt, type the following command, and then press Enter:

$logFile = "C:\Logs\Log.txt"

6. To view the value of $logFile, type the following command, and then press Enter:

$logFile

7. To set the value of $service to the W32Time service, type the following command, and then press
Enter:

$service = Get-Service W32Time

8. To display the value of $service, type the following command, and then press Enter:

$service

9. To display $logFile as part of a text message on screen, type the following command, and then press
Enter:

Write-Host "The log file location is $logFile"

10. To view all of the properties of the service object stored in $service, type the following command, and
then press Enter:

$service | Format-List *

11. To view the Status property of $service, type the following command, and then press Enter:

$service.status
7-4 Automating Administration with Windows PowerShell

12. To view the Name and Status properties of $service, type the following command, and then press
Enter:

$service | Format-Table Name,Status

13. To view the variables in memory, type the following command, and then press Enter:

Get-Variable

14. To view the variables in memory, type the following command, and then press Enter:

Get-ChildItem Variable:

15. To view the variable type of $num1, type the following command, and then press Enter:

$num1.GetType()

16. To view the variable type of $logFile, type the following command, and then press Enter:

$logFile.GetType()

17. To view the variable type of $service, type the following command, and then press Enter:

$service.GetType()

18. To view the properties and methods of $service, type the following command, and then press Enter:

$service | Get-Member

19. To set the value of $num2 as a string of 5, type the following command, and then press Enter:

$num2 = "5"

20. To set the value of $num3 as a 32-bit integer of 5, type the following command, and then press Enter:

[Int]$num3 = "5"

21. To verify the variable type of $num2, type the following command, and then press Enter:

$num2.GetType()

22. To verify the variable type of $num3, type the following command, and then press Enter:

$num3.GetType()

23. To set $date1 as a string, type the following command, and then press Enter:

$date1 = "March 5, 2019 11:45 PM"

24. To set $date2 as a DateTime type, type the following command, and then press Enter:

[DateTime]$Date2 = "March 5, 2019 11:45 PM"

25. To verify the variable type of $date1, type the following command, and then press Enter:

$date1.GetType()
Working with variables, arrays, and hash tables 7-5

26. To verify the variable type of $date2, type the following command, and then press Enter:

$date2.GetType()

27. To attempt to convert a string to a 32-bit integer, type the following command, and then press Enter:

[Int]$num4 = "Text that can't convert"

28. To view how variable types can convert during operations, type the following command, and then
press Enter:

$num2 + $num3

29. To view how variable types can convert during operations, type the following command, and then
press Enter:

$num3 + $num2

30. To view how variable types can fail to convert during operations, type the following command, and
then press Enter:

$num3 + $logFile

31. Close the Windows PowerShell prompt.


7-6 Automating Administration with Windows PowerShell

Lesson 2
Manipulating variables
Contents:
Question and Answers 7
Resources 7
Demonstration: Manipulating strings 7
Demonstration: Manipulating dates 8
Working with variables, arrays, and hash tables 7-7

Question and Answers


Question: Why is it important to understand how to use Get-Member when manipulating variables?

Answer: The Get-Member cmdlet identifies the properties and methods that are available for a
specific variable type. You need this information to identify which actions are available by using
methods. You also use this information as a starting point for research on how to use the
methods.

Resources

Identifying methods and properties

Additional Reading: For more information on .NET Framework variable types, refer to
“System Namespace” at https://aka.ms/krlgav.

Demonstration: Manipulating strings


Demonstration Steps
1. On LON-CL1, right-click the Start button, and then click Windows PowerShell (Admin).

2. To set $logFile with a value, at the Windows PowerShell prompt, type the following command, and
then press Enter:

$logFile = "C:\Logs\log.txt"

3. To identify whether $logFile contains the text C:, type the following command, and then press Enter:

$logFile.Contains("C:")

4. To identify whether $logFile contains the text D:, type the following command, and then press Enter:

$logFile.Contains("D:")

5. To insert the text \MyScript at character 7, type the following command, and then press Enter:

$logFile.Insert(7,"\MyScript")

6. To verify that the value stored in $logFile has not changed, type the following command, and then
press Enter:

$logFile

7. To update the value of $logFile, type the following command, and then press Enter:

$logFile=$logFile.Insert(7,"\MyScript")

8. To verify that the value of $logFile has changed, type the following command, and then press Enter:

$logFile

9. To replace .txt with .htm, type the following command, and then press Enter:

$logFile.Replace(".txt",".htm")
7-8 Automating Administration with Windows PowerShell

10. To split the value of $logFile at the \ character, type the following command, and then press Enter:

$logFile.Split("\")

11. To view only the last item from the split, type the following command, and then press Enter:

$logFile.Split("\") | Select -Last 1

12. To convert the value to uppercase letters, type the following command, and then press Enter:

$logFile.ToUpper()

13. To convert the value to lowercase letters, type the following command, and then press Enter:

$logFile.ToLower()

14. Close the Windows PowerShell prompt.

Demonstration: Manipulating dates


Demonstration Steps
1. On LON-CL1, right-click the Start button, and then click Windows PowerShell (Admin).
2. To put the current date and time in the variable $date, at the Windows PowerShell prompt, type the
following command, and then press Enter:

$date = Get-Date

3. To display the value of $date, at the Windows PowerShell prompt, type the following command, and
then press Enter:

$date

4. To display the Hour property of $date, type the following command, and then press Enter:

$date.Hour

5. To display the Minute property of $date, type the following command, and then press Enter:

$date.Minute

6. To display the Day property of $date, type the following command, and then press Enter:

$date.Day

7. To display the DayOfWeek property of $date, type the following command, and then press Enter:

$date.DayOfWeek

8. To display the Month property of $date, type the following command, and then press Enter:

$date.Month

9. To display the Year property of $date, type the following command, and then press Enter:

$date.Year
Working with variables, arrays, and hash tables 7-9

10. To add 100 days to $date, type the following command, and then press Enter:

$date.AddDays(100)

11. To subtract 60 days from $date, type the following command, and then press Enter:

$date.AddDays(-60)

12. To display $date as a long date string, type the following command, and then press Enter:

$date.ToLongDateString()

13. To display $date as a short date string, type the following command, and then press Enter:

$date.ToShortDateString()

14. To display $date as a long time string, type the following command, and then press Enter:

$date.ToLongTimeString()

15. To display $date as a short time string, type the following command, and then press Enter:

$date.ToShortTimeString()

16. Close the Windows PowerShell prompt.


7-10 Automating Administration with Windows PowerShell

Lesson 3
Manipulating arrays and hash tables
Contents:
Question and Answers 11
Demonstration: Manipulating arrays and arraylists 11
Demonstration: Manipulating hash tables 12
Working with variables, arrays, and hash tables 7-11

Question and Answers


Question: Why is it important to understand the difference between an array and an arraylist?

Answer: The arrays that Windows PowerShell creates by default are fixed-size arrays.
Consequently, you cannot use the add or remove methods. This means that arrays have relatively
low performance when you work with large datasets.
If instead you choose to create an arraylist, they do not have a fixed size. Therefore, you can add
or remove items from the arraylist and have better performance for large datasets.

Demonstration: Manipulating arrays and arraylists


Demonstration Steps
1. On LON-CL1, right-click the Start button, and then click Windows PowerShell (Admin).

2. To set $computers to be an array of strings, at the Windows PowerShell prompt, type the following
command, and then press Enter:

$computers = "LON-DC1","LON-SRV1","LON-CL1"

3. To set $users to be an array of user objects, type the following command, and then press Enter:

$users = Get-ADUser -Filter *

4. To view the contents of the $computers array, type the following command, and then press Enter:

$computers

5. To view the contents of the $users array, type the following command, and then press Enter:

$users

6. To view the number of items in $users, type the following command, and then press Enter:

$users.count

7. To view the user object at index 125 of $users, type the following command, and then press Enter:

$users[125]

8. To view the properties and methods available for the items in $computers, type the following
command, and then press Enter:

$computers | Get-Member

9. To view the properties and methods available for the items in $users, type the following command,
and then press Enter:

$users | Get-Member

10. To view the UserPrincipalName property for a user object in the array, type the following command,
and then press Enter:

$users[125].UserPrincipalName
7-12 Automating Administration with Windows PowerShell

11. To add an item to $computers, type the following command, and then press Enter:

$computers += "LON-SRV2"

12. To verify that the item was added, type the following command, and then press Enter:

$computers

13. To create an arraylist containing user objects, type the following command, and then press Enter:

[System.Collections.ArrayList]$usersList = Get-ADUser -Filter *

14. To identify whether $usersList has a fixed size, type the following command, and then press Enter:

$usersList.IsFixedSize

15. To view the number of items in $arrayList, type the following command, and then press Enter:

$usersList.count

16. To view a single item in $arrayList, type the following command, and then press Enter:

$usersList[125]

17. To remove an item in $arrayList, type the following command, and then press Enter:

$usersList.RemoveAt(125)

18. To verify that the item count is reduced by one, type the following command, and then press Enter:

$usersList.count

19. To verify that the item at index 125 has changed, type the following command, and then press Enter:

$usersList[125]

20. Close the Windows PowerShell prompt.

Demonstration: Manipulating hash tables


Demonstration Steps
1. On LON-CL1, right-click the Start button, and then click Windows PowerShell (Admin).

2. To create a hash table with the names of users and a department for each, at the Windows
PowerShell prompt, type the following command, and then press Enter:

$users = @{"Lara"="IT";"Peter"="Managers";"Sang"="Sales"}

3. To view the contents of the hash table, type the following command, and then press Enter:

$users

4. To view the department for a single user, type the following command, and then press Enter:

$users.Lara
Working with variables, arrays, and hash tables 7-13

5. To update the department for a user, type the following command, and then press Enter:

$users.Sang = "Marketing"

6. To verify that the department was updated, type the following command, and then press Enter:

$users

7. To add a new user, type the following command, and then press Enter:

$users.Add("Tia","Research")

8. To remove a user, type the following command, and then press Enter:

$users.Remove("Sang")

9. To verify the added and removed users, type the following command, and then press Enter:

$users

10. To create a new hash table for a calculated property, type the following command, and then press
Enter:

$prop = @{n="Size(KB)";e={$_.Length/1KB}}

11. To view the hash table, type the following command, and then press Enter:

$prop

12. To view the name and size of the files in C:\Windows, type the following command, and then press
Enter:

Get-ChildItem C:\Windows -File | Format-Table Name,Length

13. To view the size of files by using the calculated properly, type the following command, and then press
Enter:

Get-ChildItem C:\Windows -File | Format-Table Name,$prop

14. Close the Windows PowerShell prompt.


7-14 Automating Administration with Windows PowerShell

Module Review and Takeaways


Review Questions
Question: You have queried a list of computes from AD DS and placed them into a variable. When you
attempt to remove one of the computers from the variable by using the Remove() method, there is an
error. What is the most likely cause of this error?

Answer: If you did not define the variable as an arraylist, it would be automatically created as an
array. You cannot use the Add() or Remove() method with an array because it has a fixed size.
You must define the variable as an arraylist to be able to add and remove items.
Question: You have placed the value “February 20, 2018” into a variable. What type of variable will it be?

Answer: Text enclosed in quotes is interpreted as a string unless you specify the type of variable
it should be. For example: [DateTime]$date=”February 20, 2018”.
Working with variables, arrays, and hash tables 7-15

Lab Review Questions and Answers


Lab: Working with variables
Question and Answers
Question: In the “Using arrays” exercise, why did user objects in $mktgUsers not update with the new
department name?

Answer: When you query data and place it in a variable, the data in the variable is a snapshot in
time. There is no mechanism to dynamically update the data in the variable. If you want the data
in the variable to be updated, you need to query the data again.

Question: In Exercise 1, you replaced C: with D: in the variable $logPath. Why is it better to include colon
than simply replace C with D?

Answer: In a file path, the colon character only appears once. By including the colon as part of
the text that is replaced, you ensure that only the drive letter is updated. If you did not include
the colon and if the path contained the character C at any other location, it would be replaced as
well.
Basic scripting 8-1

Module 8
Basic scripting
Contents:
Lesson 1: Introduction to scripting 2

Lesson 2: Scripting constructs 6


Lesson 3: Importing data from files 8

Module Review and Takeaways 11

Lab Review Questions and Answers 12


8-2 Automating Administration with Windows PowerShell

Lesson 1
Introduction to scripting
Contents:
Resources 3
Demonstration: Setting the script execution policy 3
Demonstration: Digitally signing a script 4
Basic scripting 8-3

Resources

Modifying scripts

Additional Reading: The PowerShell gallery is located at https://aka.ms/ue14hl.


Additional Reading: The Script Center repository is located at https://aka.ms/g14v8f.

What is the PowerShellGet module?

Additional Reading: For more information about creating a NuGet feed, refer to “Hosting
your own NuGet feeds” at https://aka.ms/vm0ys1.
Additional Reading: For more information about all of the PowerShellGet cmdlets, refer to
“PowerShellGet cmdlet reference” at https://aka.ms/tykgas.

Windows PowerShell and AppLocker

Additional Reading: For more information about ConstrainedLanguage mode, refer to


about_Language_Modes in the Windows PowerShell help or “About Language Modes” at
https://aka.ms/nxcyid.

Demonstration: Setting the script execution policy


Demonstration Steps
1. On LON-CL1, on the taskbar, click File Explorer, and then browse to E:\Mod08\Democode.
2. Right-click HelloWorld.txt, and then click Rename.

3. Change the name to HelloWorld.ps1, and then press Enter.

4. Click Yes to confirm that you want to change the file extension.
5. Double-click HelloWorld.ps1.

6. Close Notepad.

7. Right-click HelloWorld.ps1, and then click Run with PowerShell. Close PowerShell.

8. Close File Explorer.

9. Click Start, type powersh, and then click Windows PowerShell.

10. To change the prompt location, at the Windows PowerShell prompt, type the following command,
and then press Enter:

Set-Location E:\Mod08\Democode

11. To verify that HelloWorld.ps1 is in the current directory, at the Windows PowerShell prompt, type
the following command, and then press Enter:

Get-ChildItem HelloWorld.ps1
8-4 Automating Administration with Windows PowerShell

12. To run HelloWorld.ps1 by using the full path, at the Windows PowerShell prompt, type the following
command, and then press Enter:

E:\Mod08\Democode\HelloWorld.ps1

13. To verify you cannot run HelloWorld.ps1 without specifying a path, at the Windows PowerShell
prompt, type the following command, and then press Enter:

HelloWorld.ps1

14. To run HelloWorld.ps1 in the current directory, at the Windows PowerShell prompt, type the
following command, and then press Enter:

.\HelloWorld.ps1

15. To view the current execution policy, at the Windows PowerShell prompt, type the following
command, and then press Enter:

Get-ExecutionPolicy

16. To prevent all scripts from running, at the Windows PowerShell prompt, type the following command,
and then press Enter:

Set-ExecutionPolicy Restricted

17. Type Y and press Enter.

18. To verify that all scripts are blocked, at the Windows PowerShell prompt, type the following
command, and then press Enter:

.\HelloWorld.ps1

19. To allow all scripts to be run, at the Windows PowerShell prompt, type the following command, and
then press Enter:

Set-ExecutionPolicy Unrestricted

20. Type Y and press Enter.


21. Leave the Windows PowerShell prompt open for the next demonstration.

Demonstration: Digitally signing a script


Demonstration Steps

Install a code signing certificate


1. On LON-CL1, click Start, type mmc, and then click mmc.
2. In the MMC console, click File, and then click Add/Remove Snap-in.

3. In the Add or Remove Snap-ins window, click Certificates, and then click Add.

4. In the Certificates snap-in dialog box, click My user account, and then click Finish.
5. In the Add or Remove Snap-ins window, click OK.

6. In the MMC console, expand Certificates - Current User, and then click Personal.
7. Right-click Personal, point to All Tasks, and then click Request New Certificate.

8. In the Certificate Enrollment wizard, on the Before You Begin page, click Next.
Basic scripting 8-5

9. On the Select Certificate Enrollment Policy page, click Active Directory Enrollment Policy, and
then click Next.

10. On the Request Certificates page, select the Adatum Code Signing check box, and then click
Enroll.
11. On the Certificate Installation Results page, click Finish.

12. In the MMC console, expand Personal, and then click Certificates to verify that the new code
signing certificate is present.

13. Close the MMC console, and then click No at the prompt to save the console settings.

Digitally sign a certificate


1. To view the code signing certificates installed for the current user, at the Windows PowerShell
prompt, type the following command, and then press Enter:

Get-ChildItem Cert:\CurrentUser\My\ -CodeSigningCert

2. To place the code signing certificate in a variable, at the Windows PowerShell prompt, type the
following command, and then press Enter:

$cert = Get-ChildItem Cert:\CurrentUser\My\ -CodeSigningCert

3. To digitally sign a script, at the Windows PowerShell prompt, type the following command, and then
press Enter:

Set-AuthenticodeSignature -FilePath E:\Mod08\Democode\HelloWorld.ps1 -Certificate


$cert

View the digital signature


1. On the taskbar, click File Explorer, and then browse to E:\Mod08\Democode.
2. Double-click HelloWorld.txt, and then verify that a digital signature has been added.

3. Close the Windows PowerShell prompt.


8-6 Automating Administration with Windows PowerShell

Lesson 2
Scripting constructs
Contents:
Demonstration: Using a ForEach loop 7
Demonstration: Using the If construct 7
Demonstration: Using the Switch construct 7
Basic scripting 8-7

Demonstration: Using a ForEach loop


Demonstration Steps
1. On LON-CL1, open File Explorer, and then browse to E:\Mod08\Democode.

2. Right-click 10961C_Mod08_Demo3.ps1, and then click Edit.

3. In Windows PowerShell ISE, review the code.

4. Press F5 to run the script.

5. Close Windows PowerShell ISE.

Demonstration: Using the If construct


Demonstration Steps
1. On LON-CL1, open File Explorer and browse to E:\Mod08\Democode.
2. Right-click 10961C_Mod08_Demo4.ps1, and then click Edit.

3. In Windows PowerShell ISE, review the code.

4. Press F5 to run the script.


5. In line 1, update the value of $freeSpace to 11GB.

6. Press F5 to run the script, and then click Yes to save the script.

7. In line 1, update the value of $freeSpace to 22GB.


8. Press F5 to run the script, and then click Yes to save the script.
9. Close Windows PowerShell ISE.

Demonstration: Using the Switch construct


Demonstration Steps
1. On LON-CL1, open File Explorer, and then browse to E:\Mod08\Democode.
2. Right-click 10961C_Mod08_Demo5.ps1, and then click Edit.

3. In Windows PowerShell ISE, review the code.

4. Press F5 to run the script.

5. In line 1, update the value of $computer to VAN-SRV1.

6. Press F5 to run the script, and then click Yes to save the script.

7. In line 1, update the value of $computer to SEA-CL1.

8. Press F5 to run the script, and then click Yes to save the script.
9. In line 1, update the value of $computer to SEA-RDP.

10. Press F5 to run the script, and then click Yes to save the script.

11. Close Windows PowerShell ISE.


8-8 Automating Administration with Windows PowerShell

Lesson 3
Importing data from files
Contents:
Demonstration: Importing data 9
Basic scripting 8-9

Demonstration: Importing data


Demonstration Steps
1. On LON-CL1, click Start, type Powersh, and then click Windows PowerShell.

2. To retrieve data from a text file, at the Windows PowerShell prompt, type the following command,
and then press Enter:

Get-Content E:\Mod08\Democode\computers.txt

3. To place data from a text file into an array, at the Windows PowerShell prompt, type the following
command, and then press Enter:

$computers = Get-Content E:\Mod08\Democode\computers.txt

4. To display the number of items in the $computers array, at the Windows PowerShell prompt, type the
following command, and then press Enter:

$computers.count

5. To display the items in the $computers array, at the Windows PowerShell prompt, type the following
command, and then press Enter:

$computers

6. To import CSV data, at the Windows PowerShell prompt, type the following command, and then
press Enter:

Import-Csv E:\Mod08\Democode\users.csv

7. To import CSV data into an array, at the Windows PowerShell prompt, type the following command,
and then press Enter:

$users = Import-Csv E:\Mod08\Democode\users.csv

8. To display the count of items in the array, at the Windows PowerShell prompt, type the following
command, and then press Enter:

$users.count

9. To display the first item in the array, at the Windows PowerShell prompt, type the following
command, and then press Enter:

$users[0]

10. To display the property named First for the item, at the Windows PowerShell prompt, type the
following command, and then press Enter:

$users[0].First

11. To import data from an XML file, at the Windows PowerShell prompt, type the following command,
and then press Enter:

Import-Clixml E:\Mod08\Democode\users.xml
8-10 Automating Administration with Windows PowerShell

12. To import XML data into an array, at the Windows PowerShell prompt, type the following command,
and then press Enter:

$usersXml = Import-Clixml E:\Mod08\Democode\users.xml

13. To view the number of items in the array, at the Windows PowerShell prompt, type the following
command, and then press Enter:

$usersXml.count

14. To view the first item in the array, at the Windows PowerShell prompt, type the following command,
and then press Enter:

$usersXml[0]

15. To view the properties for the items in the array, at the Windows PowerShell prompt, type the
following command, and then press Enter:

$usersXml | Get-Member

16. Close the Windows PowerShell prompt.


Basic scripting 8-11

Module Review and Takeaways


Review Questions
Question: When importing data, what is the primary consideration when selecting which cmdlet to use?

Answer: The format of the data should be the primary consideration. You choose the cmdlet to
match the type of data that is being imported. If you have a choice of data formats, you can
select the format that you are most comfortable with or is easiest to work with.

Question: Why is the ForEach construct used more often than the For construct?

Answer: Many Windows PowerShell scripts work on a set of data that is obtained from a query
or an imported file. Those data sets are of an unknown size, which is simpler to manage by using
ForEach. The For construct is typically used only when an action is being performed a specific
number of times.
8-12 Automating Administration with Windows PowerShell

Lab Review Questions and Answers


Lab: Basic scripting
Question and Answers
Question: When would you prefer to use a code signing certificate from a third-party certification
authority rather than an internal certification authority?

Answer: A code signing certificate from an internal certification authority will only be trusted by
internal clients. If you are signing scripts that will be used outside your organization, you should
get the certificate from a third-party certification authority.

Question: In Exercise 2, you configured the ipPhone attribute for a group of test users. How would you
update that script for a larger set of users as the solution is deployed to the rest of the organization?

Answer: The script in Exercise 2 modified the ipPhone attribute for members of the
IPPhoneTest group. When this functionality is being deployed to the remainder of the
organization, the query for users will need to be expanded. For example, the script could be
modified to work for individual organizational units as the new system is deployed to each
department.
Advanced scripting 9-1

Module 9
Advanced scripting
Contents:
Lesson 1: Accepting user input 2

Lesson 2: Overview of script documentation 6


Lesson 3: Troubleshooting and error handling 9

Lesson 4: Functions and modules 13

Module Review and Takeaways 16


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

Lesson 1
Accepting user input
Contents:
Question and Answers 3
Demonstration: Obtaining user input 3
Demonstration: Obtaining user input by using parameters 4
Advanced scripting 9-3

Question and Answers


Question: Why is it useful to assign default values to parameters in a script?

Answer: Assigning a default value ensures that a parameter has a value. This ensures that your
script does not generate an error when that value is missing. However, not all parameters are
suitable for a default value. For example, a default value is not useful for a parameter that
specifies a remote computer because a remote computer name is unpredictable.

Demonstration: Obtaining user input


Demonstration Steps
1. On LON-CL1, click Start, type powersh, and click Windows PowerShell.

2. To obtain user input by using Read-Host, at the Windows PowerShell prompt, type the following
command, and then press Enter. At the prompt provide a number for the days:

$days = Read-Host "Enter the number of days"

3. To view the data obtained by Read-Host, at the Windows PowerShell prompt, type the following
command, and then press Enter:

$days

4. To obtain a credential, at the Windows PowerShell prompt, type the following command, and then
press Enter:

$cred = Get-Credential

5. To display the credential information, at the Windows PowerShell prompt, type the following
command, and then press Enter:

$cred | Format-List

6. To store the credential in a file, at the Windows PowerShell prompt, type the following command,
and then press Enter:

$cred | Export-Clixml -Path E:\Mod09\Democode\cred.xml

7. To view the content of the file, at the Windows PowerShell prompt, type the following command, and
then press Enter:

Get-Content E:\Mod09\Democode\cred.xml

8. To display a list of computer accounts in Out-GridView, at the Windows PowerShell prompt, type the
following command, and then press Enter:

Get-ADComputer -Filter * | Out-GridView

9. Close the Out-GridView window.

10. To allow a single section in the Out-GridView window, at the Windows PowerShell prompt, type the
following command, and then press Enter:

$computer = Get-ADComputer -Filter * | Out-GridView -OutputMode Single

11. In the Out-GridView window, click LON-CL1 and click OK.


9-4 Automating Administration with Windows PowerShell

12. To display the selected object, at the Windows PowerShell prompt, type the following command, and
then press Enter:

$computer

13. Close the Windows PowerShell prompt.

Demonstration: Obtaining user input by using parameters


Demonstration Steps
1. Click Start, type power, and click Windows PowerShell.

2. To rename a text file to a script file, at the Windows PowerShell prompt, type the following command,
and then press Enter:

Rename-Item E:\Mod09\Democode\10961C_Mod09_Demo02.txt 10961C_Mod09_Demo02.ps1

3. Click Start, type ise, and click Windows PowerShell ISE.


4. In Windows PowerShell ISE, click the File menu and click Open.

5. In the Open window, in the address bar, type E:\Mod09\Democode and press Enter.
6. Click 10961C_Mod09_Demo02.ps1 and click Open.
7. Review the code and leave Windows PowerShell ISE open.

8. To set the current directory, at the Windows PowerShell prompt, type the following command, and
then press Enter:

Set-Location E:\Mod09\Democode

9. To pass values to the script by position, at the Windows PowerShell prompt, type the following
command, and then press Enter:

.\10961C_Mod09_Demo02.ps1 LON-DC1 300

10. To pass values to the script by parameter name, at the Windows PowerShell prompt, type the
following command, and then press Enter:

.\10961C_Mod09_Demo02.ps1 -EventID 300 -ComputerName LON-DC1

11. To view the results when no parameter data is provided, at the Windows PowerShell prompt, type the
following command, and then press Enter:

.\10961C_Mod09_Demo02.ps1

12. In Windows PowerShell ISE, on line 2, after $ComputerName, type =(Read-Host “Enter computer
name”).

13. On line 3, after $EventID, type =300.


14. Click the File menu and click Save.
Advanced scripting 9-5

15. To view the results when no parameter data is provided, at the Windows PowerShell prompt, type the
following command, and then press Enter:

.\10961C_Mod09_Demo02.ps1

16. When prompted for a computer name, type LON-DC1, and then press Enter.

17. Close Windows PowerShell ISE and the Windows PowerShell prompt.
9-6 Automating Administration with Windows PowerShell

Lesson 2
Overview of script documentation
Contents:
Question and Answers 7
Demonstration: Adding comments to a script 7
Demonstration: Adding help information to a script 8
Advanced scripting 9-7

Question and Answers


Question: Why is it important to add comments within scripts?

Answer: Comments are useful for other administrators who are trying to interpret your script,
and they are also useful for you. If you have not edited a script for an extended period,
comments help you understand what your thought process was during development.

Demonstration: Adding comments to a script


Demonstration Steps
1. Click Start, type power, and click Windows PowerShell.

2. To rename a text file to a script file, at the Windows PowerShell prompt, type the following command,
and then press Enter:

Rename-Item E:\Mod09\Democode\10961C_Mod09_Demo03.txt 10961C_Mod09_Demo03.ps1

3. Click Start, type ise, and click Windows PowerShell ISE.


4. In Windows PowerShell ISE, click the File menu and click Open.

5. In the Open window, in the address bar, type E:\Mod09\Democode and press Enter.
6. Click 10961C_Mod09_Demo03.ps1 and click Open.
7. In Windows PowerShell ISE, review the code.

8. To set the current directory, at the Windows PowerShell prompt, type the following command, and
then press Enter:

Set-Location E:\Mod09\Democode

9. To view the script output, at the Windows PowerShell prompt, type the following command, and then
press Enter:

.\10961C_Mod09_Demo03.ps1

10. In Windows PowerShell ISE, on line 7, type #Information for troubleshooting.


11. Click the File menu and click Save.

12. To verify that the script output has not changed, at the Windows PowerShell prompt, type the
following command, and then press Enter:

.\10961C_Mod09_Demo03.ps1

13. In Windows PowerShell ISE, on line 8 type <#.

14. On line 11, type #>.

15. Click the File menu and click Save.


16. To verify that troubleshooting information is no longer displayed, at the Windows PowerShell prompt,
type the following command, and then press Enter:

.\10961C_Mod09_Demo03.ps1

17. Close Windows PowerShell ISE and the Windows PowerShell prompt.
9-8 Automating Administration with Windows PowerShell

Demonstration: Adding help information to a script


Demonstration Steps
1. Click Start, type power, and click Windows PowerShell.

2. To rename a text file to a script file, at the Windows PowerShell prompt, type the following command,
and then press Enter:

Rename-Item E:\Mod09\Democode\10961C_Mod09_Demo04.txt Query-Bios.ps1

3. Click Start, type ise, and click Windows PowerShell ISE.

4. In Windows PowerShell ISE, click the File menu and click Open.

5. In the Open window, in the address bar, type E:\Mod09\Democode and press Enter.

6. Click Query-Bios.ps1 and click Open.

7. Click the File menu and click Open.

8. In the Open window, in the file type box, select Text Files (*.txt), click
10961C_Mod09_Demo04_Help.txt and click Open.
9. To copy the text, press Ctrl+A and then press Ctrl+C.

10. Click the Query-Bios.ps1 tab, place the cursor on line 1 and press Ctrl+V.
11. Click the File menu and click Save.

12. To change the current directory, at the Windows PowerShell prompt, type the following command,
and then press Enter:

Set-Location E:\Mod09\Democode

13. To view basic help information, at the Windows PowerShell prompt, type the following command,
and then press Enter:

Get-Help .\Query-Bios.ps1

14. To see the examples in the Windows PowerShell help, at the Windows PowerShell prompt, type the
following command, and then press Enter:

Get-Help .\Query-Bios.ps1 -Examples

15. To view all of the help information, at the Windows PowerShell prompt, type the following command,
and then press Enter:

Get-Help .\Query-Bios.ps1 -Full

16. Close the Windows PowerShell ISE window and the Windows PowerShell prompt.
Advanced scripting 9-9

Lesson 3
Troubleshooting and error handling
Contents:
Question and Answers 10
Demonstration: Troubleshooting a script 10
Demonstration: Handling errors 11
9-10 Automating Administration with Windows PowerShell

Question and Answers


Question: What is the purpose of using breakpoints?

Answer: Breakpoints allow you to pause script processing and interact with the variables in the
script. You can query variable values or modify them. You can use this information for
troubleshooting.

Demonstration: Troubleshooting a script


Demonstration Steps
1. Click Start, type power, and click Windows PowerShell.

2. To rename a text file to a script file, at the Windows PowerShell prompt, type the following command,
and then press Enter:

Rename-Item E:\Mod09\Democode\10961C_Mod09_Demo05.txt 10961C_Mod09_Demo05.ps1

3. Click Start, type ise, and click Windows PowerShell ISE.


4. In Windows PowerShell ISE, click the File menu and click Open.

5. In the Open window, in the address bar, type E:\Mod09\Democode and press Enter.
6. Click 10961C_Mod09_Demo05.ps1 and click Open.
7. In Windows PowerShell ISE, review the code.

8. To set the current directory, at the Windows PowerShell prompt, type the following command, and
then press Enter:

Set-Location E:\Mod09\Democode

9. To view the script output, at the Windows PowerShell prompt, type the following command, and then
press Enter:

.\10961C_Mod09_Demo05.ps1

10. To view the error, at the Windows PowerShell prompt, type the following command, and then press
Enter:

$Error[0]

11. To clear the $Error variable, at the Windows PowerShell prompt, type the following command, and
then press Enter:

$Error.Clear()

12. To create a breakpoint, at the Windows PowerShell prompt, type the following command, and then
press Enter:

Set-PSBreakPoint .\10961C_Mod09_Demo05.ps1 -Line 5

13. To run the script, at the Windows PowerShell prompt, type the following command, and then press
Enter:

.\10961C_Mod09_Demo05.ps1
Advanced scripting 9-11

14. To view the value $ComputerName, at the Windows PowerShell prompt, type the following
command, and then press Enter:

$ComputerName

15. To test the value $ComputerName, at the Windows PowerShell prompt, type the following
command, and then press Enter:

$ComputerName -eq $null

16. To test the value $ComputerName, at the Windows PowerShell prompt, type the following
command, and then press Enter:

$ComputerName -eq “”

17. To exit the debug prompt, at the Windows PowerShell prompt, type the following command, and
then press Enter:

exit

18. In Windows PowerShell ISE, on line 5, change $null to “”.


19. Click the File menu and click Save.

20. To view all breakpoints, at the Windows PowerShell prompt, type the following command, and then
press Enter:

Get-PSBreakPoint

21. To remove all breakpoints, at the Windows PowerShell prompt, type the following command, and
then press Enter:

Get-PSBreakPoint | Remove-PSBreakPoint

22. To run the script, at the Windows PowerShell prompt, type the following command, and then press
Enter:

.\10961C_Mod09_Demo05.ps1

23. Close Windows PowerShell ISE and the Windows PowerShell prompt.

Demonstration: Handling errors


Demonstration Steps
1. Click Start, type power, and click Windows PowerShell.

2. To rename a text file to a script file, at the Windows PowerShell prompt, type the following command,
and then press Enter:

Rename-Item E:\Mod09\Democode\10961C_Mod09_Demo06.txt 10961C_Mod09_Demo06.ps1

3. Click Start, type ise, and click Windows PowerShell ISE.

4. In Windows PowerShell ISE, click the File menu and click Open.
5. In the Open window, in the address bar, type E:\Mod09\Democode and press Enter.

6. Click 10961C_Mod09_Demo06.ps1 and click Open.


9-12 Automating Administration with Windows PowerShell

7. Review the code in the script and note that Section 1 with no error checking is the current code.
Section 2 with error checking has a block comment around it.

8. Press F5 to run the script. Notice that an error is generated because LON-SVR1 is not available.
9. On line 3, type <#.

10. On line 9, type #>.

11. On line 10, remove <#.


12. On line 22, remove #>.

13. Click the File menu and click Save.

14. Press F5 to run the script. Notice that no error is generated because the error handling displays a
message instead.

15. Close Windows PowerShell ISE and the Windows PowerShell prompt.
Advanced scripting 9-13

Lesson 4
Functions and modules
Contents:
Question and Answers 14
Demonstration: Creating a function in a script 14
Demonstration: Creating a module from a function 14
9-14 Automating Administration with Windows PowerShell

Question and Answers


Question: Why would you prefer to use script modules for functions instead of dot sourcing?

Answer: One big benefit of using script modules is that they are automatically available to all
scripts on a computer. If you have placed your modules in a NuGet repository, you can use
Install-Module to retrieve them from the repository and install them.

Demonstration: Creating a function in a script


Demonstration Steps
1. Click Start, type power, and click Windows PowerShell.

2. To rename a text file to a script file, at the Windows PowerShell prompt, type the following command,
and then press Enter:

Rename-Item E:\Mod09\Democode\10961C_Mod09_Demo07.txt 10961C_Mod09_Demo07.ps1

3. Click Start, type ise, and click Windows PowerShell ISE.


4. In Windows PowerShell ISE, click the File menu and click Open.

5. In the Open window, in the address bar, type E:\Mod09\Democode and press Enter.
6. Click 10961C_Mod09_Demo07.ps1 and click Open.
7. Review the code.

8. To set the prompt location, at the Windows PowerShell prompt, type the following command, and
then press Enter:

Set-Location E:\Mod09\Democode

9. To view the size of a folder, at the Windows PowerShell prompt, type the following command, and
then press Enter:

.\10961C_Mod09_Demo07.ps1 -Path “C:\Windows”

10. To view the size of a folder including subfolders, at the Windows PowerShell prompt, type the
following command, and then press Enter:

.\10961C_Mod09_Demo07.ps1 -Path “C:\Program Files” -Recurse

11. In Windows PowerShell ISE, insert a blank line at line 1, and then type Function Get-FolderSize {.

12. On the last line, type }.


13. At the end of the file add Get-FolderSize -Path “C:\Program Files” -Recurse.

14. At the end of the file, add Get-FolderSize -Path C:\Windows.

15. Click the File menu and click Save.


16. Press F5 to run the script, and then review the results.

17. Close Windows PowerShell ISE and the Windows PowerShell prompt.

Demonstration: Creating a module from a function


Demonstration Steps
1. Click Start, type power, and click Windows PowerShell.
Advanced scripting 9-15

2. To set the prompt location, at the Windows PowerShell prompt, type the following command, and
then press Enter:

Set-Location E:\Mod09\Democode\

3. To copy and rename a script file, at the Windows PowerShell prompt, type the following command,
and then press Enter:

Copy-Item .\10961C_Mod09_Demo07.ps1 .\FolderFunctions.psm1

4. Click Start, type ise, and click Windows PowerShell ISE.

5. In Windows PowerShell ISE, click the File menu and click Open.
6. In the Open window, in the address bar, type E:\Mod09\Democode and press Enter.

7. Click FolderFunctions.psm1 and click Open.

8. Review the code.


9. Remove the last two lines that call the function.

10. Click the File menu and click Save.

11. Close Windows PowerShell ISE.


12. To create a folder for the module, at the Windows PowerShell prompt, type the following command,
and then press Enter:

New-Item -Type Directory “C:\Program Files\WindowsPowerShell\Modules\FolderFunctions”

13. To copy the .psm1 file, at the Windows PowerShell prompt, type the following command, and then
press Enter:

Copy-Item .\FolderFunctions.psm1 “C:\Program


Files\WindowsPowerShell\Modules\FolderFunctions”

14. To verify that the module is recognized, at the Windows PowerShell prompt, type the following
command, and then press Enter:

Get-Module -ListAvailable F*

15. To verify that the module is not loaded, at the Windows PowerShell prompt, type the following
command, and then press Enter:

Get-Module

16. To use the function in the module, at the Windows PowerShell prompt, type the following command,
and then press Enter:

Get-FolderSize -Path C:\Windows

17. To verify that the module is loaded, at the Windows PowerShell prompt, type the following
command, and then press Enter:

Get-Module

18. Close the Windows PowerShell prompt.


9-16 Automating Administration with Windows PowerShell

Module Review and Takeaways


Review Questions
Question: Is it possible to store credentials to disk for later reuse?

Answer: Yes, you can store a set of credentials to disk by using Export-Clixml. The results on
disk are encrypted and can only be decrypted by the user who originally encrypted them. This
means that storing credentials is useful for single users, but is not useful for scripts that are
shared among multiple users.
Question: Is it possible to use Try..Catch and provide different responses for different errors?

Answer: Yes, it is possible. A single Try statement can have multiple Catch statements associated
with it. You can provide a specific error type to make a Catch statement specific to that error.
Advanced scripting 9-17

Lab Review Questions and Answers


Lab A: Accepting data from users
Question and Answers
Question: You configured a switch parameter to indicate whether alternate credentials are required.
What are the possible values for a switch parameter?

Answer: A switch parameter has a value of $true or $false.


Question: Why did you use Get-CimInstance instead of Get-WmiObject in this script?

Answer: In general, Common Information Model (CIM) is preferred over Windows Management
Instrumentation (WIM) because Microsoft has deprecated WMI. However, in this case, there was
also a requirement to use WS-MAN. Get-CimInstance uses WS-MAN. Get-WmiObject uses
DCOM.

Lab B: Implementing functions and modules

Question and Answers


Question: If you use Try..Catch to create a friendly error message, what type of information should be
included in that error message?

Answer: A friendly error message needs to contain enough information to be useful. In this lab,
indicating that there was an error writing to file is useful, but if you include the path of the file it
is even more useful. Users can review the path to verify whether it is what they expected.

Question: How do you call a function from within a script?


Answer: Each function that you define has a name. To call the function, use that name, and then
Windows PowerShell identifies it as that function. When you call the function, you use parameters
to pass data to it, just as you would with a script.
Administering remote computers 10-1

Module 10
Administering remote computers
Contents:
Lesson 1: Using basic Windows PowerShell remoting 2

Lesson 2: Using advanced Windows PowerShell remoting techniques 4


Lesson 3: Using PSSessions 6

Module Review and Takeaways 10

Lab Review Questions and Answers 11


10-2 Automating Administration with Windows PowerShell

Lesson 1
Using basic Windows PowerShell remoting
Contents:
Question and Answers 3
Demonstration: Enabling and using remoting 3
Administering remote computers 10-3

Question and Answers


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

Answer: A computer might not always 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 security
concerns for some organizations. However, remoting offers several features that enable
organizations to help secure, monitor, and 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: Enabling and using remoting


Demonstration Steps
1. Click the Start menu, right-click the Windows PowerShell tile, and click Run as Administrator.
2. To ensure that you have the correct execution policy in place, in the Windows PowerShell command
window, type the following command, and then press Enter:

Set-ExecutionPolicy RemoteSigned

3. In the Execution Policy Change dialog box, click Yes.


4. Type the following command, and then press Enter:

Enable-PSRemoting

If you receive an error about a network connection being Public, point out the error to students, and
explain that this is a common error. Then run the following command:

Enable-PSRemoting -SkipNetworkProfileCheck

5. Click Yes or press Y to confirm all dialog boxes.

6. Type the following command, and then press Enter:

Enter-PSSession –ComputerName LON-DC1

7. Type the following command, and then press Enter:

Get-Process

8. Type the following command, and then press Enter:

Exit-PSSession

9. Type the following command, and then press Enter:

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


Security –Newest 10 }

Leave the Windows PowerShell command window open for the next demonstration.
10-4 Automating Administration with Windows PowerShell

Lesson 2
Using advanced Windows PowerShell remoting
techniques
Contents:
Question and Answers 5
Demonstration: Sending local variables to a remote computer 5
Administering remote computers 10-5

Question and Answers


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

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: Sending local variables to a remote computer


Demonstration Steps
1. To demonstrate how the data in a variable might be provided by a user, in the Windows PowerShell
command window, type the following command, and then press Enter:

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

When you are prompted for a number of log entries that you want to view, enter any desired value
(for example, 5), and then press Enter.
2. Type the following command, and then press Enter:

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


Get-EventLog –LogName Security –newest $x }

Point out to students how you can view the number of entries you specified for the Security log.
3. Now try the Using: scope modifier. Type the following command, and then press Enter:

Invoke-Command -ComputerName lon-dc1 -ScriptBlock {Get-EventLog -LogName Security –


Newest $Using:quantity}

Point out to students that you still view the number of entries you specified for the Security log, just
as you did with -ArgumentList parameter, but the $Using: scope modifier is easier to process.
Leave the Windows PowerShell command window open for the next demonstration.
10-6 Automating Administration with Windows PowerShell

Lesson 3
Using PSSessions
Contents:
Question and Answers 7
Demonstration: Using PSSessions 7
Demonstration: Disconnected sessions 8
Demonstration: Implicit remoting 8
Administering remote computers 10-7

Question and Answers


Question: What are some potential operational concerns for PSSessions?

Answer: Because PSSessions are persistent, one concern is that lots of administrators might open
many PSSessions to a single server. That could potentially create a large amount of processing
and memory overhead on the server. You can lessen this concern by:
• Configuring remoting options appropriately to limit the number of PSSessions one
administrator can create.

• Limiting the total number of administrators who may create concurrent PSSessions on a
server.

• The default quota limit should be sufficient in most cases. In the WSMan properties,
MaxShellsPerUser is set to 5 by default.

Demonstration: Using PSSessions


Demonstration Steps
1. On the LON-CL1 virtual machine, click the Start menu, right-click the Windows PowerShell tile, and
then click Run as Administrator.

2. In the Windows PowerShell command window, type the following command, and then press Enter:

$dc = New-PSSession –ComputerName LON-DC1

3. Type the following command, and then press Enter:

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

4. Type the following command, and then press Enter:

Get-PSSession

5. Type the following command, and then press Enter:

$dc

6. Type the following command, and then press Enter:

Enter-PSSession –Session $dc

7. Type the following command, and then press Enter:

Get-Process

8. Type the following command, and then press Enter:

Exit-PSSession

9. Type the following command, and then press Enter:

$dc
10-8 Automating Administration with Windows PowerShell

10. Type the following command, and then press Enter:

Invoke-Command –Session $all –ScriptBlock { Get-Service | Where { $_.Status –eq


'Running' }}

11. Type the following command, and then press Enter:

$dc | Remove-PSSession

12. Type the following command, and then press Enter:

Get-PSSession

13. Type the following command, and then press Enter:

Get-PSSession | Remove-PSSession

14. Leave the Windows PowerShell command window open for the next demonstration.

Demonstration: Disconnected sessions


Demonstration Steps
1. In the Windows PowerShell command window, in order to create a variable named $dc, which creates
a PSSession, type the following command, and then press Enter:

$dc = New-PSSession –ComputerName LON-DC1

2. To disconnect from the PSSession created above, type the following command, and then press Enter:

Disconnect-PSSession –Session $dc

3. To open the disconnected PSSession, type the following command, and then press Enter:

Get-PSSession –ComputerName LON-DC1

4. To reconnect to the PSSession, type the following command, and then press Enter:

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

5. To confirm that the PSSession is available, type the following command, and then press Enter:

$dc

6. To close the PSSession, type the following command, and then press Enter:

Remove-PSSession –Session $dc

7. Leave the Windows PowerShell command window open for the next demonstration.

Demonstration: Implicit remoting


Demonstration Steps
1. On 10961C-LON-CL1, in the Windows PowerShell command window, type the following command,
and then press Enter:

$dc = New-PSSession LON-DC1


Administering remote computers 10-9

2. Type the following command, and then press Enter:

Get-Module –PSSession $dc –ListAvailable

3. Type the following command, and then press Enter:

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

4. Type the following command, and then press Enter:

Help Get-RemADUser

Note: 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, type the following command, and then press Enter:

Get-RemADUser –Filter *

6. To close the session, type the following command, and then press Enter:

$dc | Remove-PSSession

7. Type the following command, and then press Enter:

Get-RemADUser

Explain to students that the command will use implicit remoting to re-create a PSSession, and will
prompt you for input to be able to run the command successfully. Explain that if you run Get-
PSSession after this command, you will see that a new session with LON-DC1 has been re-created.
10-10 Automating Administration with Windows PowerShell

Module Review and Takeaways


Best Practice
Always consider the security implications of opening too many remote sessions. The default configuration
is tightly secured 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 (RDP), and in some ways is more secure and
controllable than many other protocols (such as RPC) that it tries to replace. IT security personnel should
take the time to thoroughly understand remoting before deciding to disable it. This is because disabling
remoting deprives administrators of a valuable management tool, frequently requiring them to take less-
secure workaround measures to restore lost functionality.

There is also concern over the CredSSP protocol that Microsoft describes as an increased security risk. This
is because it enables the delegation of credentials to remote computers, and if those computers are
compromised then the credential could also be compromised. Only trusted, managed, secured computers
should be enabled for CredSSP delegation and even so, the risk is still present. You should use constrained
delegation instead of CredSSP.

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 somewhat
difficult. Before trying to troubleshoot Windows
PowerShell remoting specifically, ensure that all
networking functionality is available. For example,
ensure firewalls have the proper ports enabled and
DNS is correctly resolving the computer name you
are using. You can use the Test-NetConnection or
the Ping command, and the Resolve-DnsName or
NSLookup commands to test for the presence of or
to ensure DNS has a proper resource record for the
remote computer.

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 10-11

Lab Review Questions and Answers


Lab A: Using basic remoting
Question and Answers
Question: You established a PSSession from LON-CL1 to LON-DC1, and then within that PSSession, you
tried to establish a PSSession back to LON-CL1. This failed. Why?

Answer: You receive an error that you cannot use the Enter-PSSession cmdlet to enter another
PSSession. By default, you cannot establish a connection through an already-established
connection.

Lab B: Using PSSessions


Question and Answers
Question: What are some of the benefits from using implicit remoting?
Answer: One benefit is that administrators do not have to install administrative tools such as
Windows 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 administrators can more centrally monitor and control access to tools. By
keeping Windows PowerShell commands on a smaller number of computers, you also can easily
update the commands as needed.
Using background jobs and scheduled jobs 11-1

Module 11
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 9


11-2 Automating Administration with Windows PowerShell

Lesson 1
Using background jobs
Contents:
Question and Answers 3
Resources 3
Demonstration: Using background jobs 3
Using background jobs and scheduled jobs 11-3

Question and Answers


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

Answer: Any long-running task is an appropriate 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.

Resources

What are background jobs?

Additional Reading: For more information on workflow jobs, refer to Automatically


resuming Windows PowerShell Workflow jobs at logon at: https://aka.ms/aj4zzl.

Demonstration: Using background jobs


Demonstration Steps
1. On LON-CL1, open the Windows PowerShell ISE as Administrator.

2. Type the following command, and then press Enter:

Enable-PSRemoting

3. Type the following command, and then press Enter:

Start-Job –ScriptBlock { Dir C:\ -Recurse } –Name LocalDir

4. Type the following command, and then press Enter:

Invoke-Command –ScriptBlock { Get-EventLog –LogName Security –Newest 100 } –


ComputerName LON-CL1,LON-DC1 –JobName RemoteLogs

5. Type the following command, and then press Enter:

Get-Job

6. Type the following command, and then press Enter:

Get-Job –Name LocalDir | Stop-Job

7. Type the following command, and then press Enter:

Receive-Job –Name LocalDir

8. Type the following command, and then press Enter:

Remove-Job –Name LocalDir

9. Type the following command, and then press Enter:

Get-Job

Repeat this step until the RemoteLogs job shows a status of Completed.
11-4 Automating Administration with Windows PowerShell

10. Type the following command, and then press Enter:

Get-Job –Name RemoteLogs -IncludeChildJob | Where location -eq 'LON-DC1' | Select -


ExpandProperty ID

Note the job ID that corresponds to the LON-DC1 job.

11. Type the following command, and then press Enter:

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

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

12. Type the following command, and then press Enter:

Receive-Job –Name RemoteLogs

13. Type the following command, and then press Enter:

Remove-Job –Name RemoteLogs

Leave the Windows PowerShell ISE open for the next demonstration.
Using background jobs and scheduled jobs 11-5

Lesson 2
Using scheduled jobs
Contents:
Question and Answers 6
Resources 6
Demonstration: Using a Windows PowerShell script as a scheduled task 6
Demonstration: Using scheduled jobs 7
11-6 Automating Administration with Windows PowerShell

Question and Answers


Question: Why would 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 type of job that combines the abilities of the Windows Task Scheduler with Windows
PowerShell manageability.

Resources
Running Windows PowerShell scripts as scheduled tasks

Reference Links: The Microsoft Script Repository is in the Microsoft Script Center, at
https://aka.ms/il71no.

Demonstration: Using a Windows PowerShell script as a scheduled task


Demonstration Steps
1. On LON-DC1, in Server Manager, click Tools, and then select Active Directory Users and
Computers.
2. In the Active Directory Users and Computers console tree, select and expand Adatum.com, and then
select Managers.

3. In the details pane of Managers, select one of the user accounts. Right-click the account, and then
select Disable Account, and then click OK in the popup window. Minimize Active Directory Users
and Computers.
4. Click Start, type Task Scheduler, and then select Task Scheduler from the content menu.

5. In the Task Scheduler, in the console tree, right-click Task Scheduler (local) and select Create task.

6. In the Create Task window, in the General tab, in the Name and Description text boxes, type
Delete Disabled User from Managers Security Group. In the Security options, select the Run
whether user is logged on or not, and then select the Run with highest privileges check box.

7. On the Triggers tab, click the New button, and in the New Trigger window, under Settings, select
Daily. In the Start time text box, change the time to 5 minutes from the current time, and then click
OK.

8. On the Action tab, click the New button. In the New Action window, in the Program/script text
box, type PowerShell.exe

9. In the Add arguments (optional): text box, type -ExecutionPolicy Bypass


E:\Labfiles\Mod11\DeleteDisabledUserManagersGroup.ps1, and then click OK. If a pop-up
window appears, select Yes.

10. On the Conditions tab, review the items, but make no changes.

11. In the Settings tab, at the bottom of the window, under If the task is already running, then the
following rule applies: click the drop-down list and select Stop the existing instance. Then click
OK.

12. In the Task Scheduler credentials pop-up, in the Password text box, type Pa55w.rd, and then click
OK.
Using background jobs and scheduled jobs 11-7

13. In the Task Scheduler, click Task Scheduler Library and then in the upper details pane, select the
Delete Disabled User from Managers Security Group item, and then in the lower details pane,
select the History tab. After the five minutes are up, click Refresh in the Actions pane. You should
see an item with Task Category of Task completed.

14. Maximize Active Directory Users and Computers. Double-click the user you disabled. Select the
Member of tab. The user should no longer be a member of the Managers security group.

Demonstration: Using scheduled jobs


Demonstration Steps
1. On LON-CL1, in Windows PowerShell ISE, type the following command, and then press Enter:

Get-Job | Remove-Job

You might 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. You run the Remove-
Job command here to clear the jobs before proceeding with the next steps.
2. Type the following command, and then press Enter:

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

3. Type the following command, and then press Enter::

Register-ScheduledJob –Trigger $trigger –Name DemoJob –ScriptBlock { Get-EventLog –


LogName Application }

4. Type the following command, and then press Enter::

Get-ScheduledJob | Select –Expand JobTriggers

Notice the Time.


5. Type the following command, and then press Enter:

Get-ScheduledJob

6. Type the following command, and then press Enter:

Get-Job

7. Type the following command, and then press Enter:

Receive-Job –Name DemoJob

8. Type the following command, and then press Enter:

Get-Job –Name DemoJob | Remove-Job


11-8 Automating Administration with Windows PowerShell

Module Review and Takeaways


Review Question
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 Windows PowerShell is not running, and you can still use it to retrieve job results.

Real-world Issues and Scenarios


Remember that scheduled jobs are defined, stored, and managed locally. There is no option for
centralized scheduled job management. For that reason, you should be careful to document job
definitions. In large environments, you might 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 Windows
available. Server 2012 and newer, and is not available on earlier
versions of the operating system. The
PSScheduledJob module is a feature of Windows
PowerShell 3.0 and newer, and it should be available
on any computer where that version of the shell is
installed.
Using background jobs and scheduled jobs 11-9

Lab Review Questions and Answers


Lab: Using background jobs and scheduled jobs
Question and Answers
Question: Get-CIMInstance does not have an –AsJob parameter. Why? How would you use Get-
CimInstance 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: 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 advanced Windows PowerShell techniques 12-1

Module 12
Using advanced Windows PowerShell techniques
Contents:
Lesson 1: Creating profile scripts 2

Lesson 2: Using advanced techniques 4


Module Review and Takeaways 9

Lab Review Questions and Answers 10


12-2 Automating Administration with Windows PowerShell

Lesson 1
Creating profile scripts
Contents:
Question and Answers 3
Demonstration: Creating a profile script 3
Using advanced Windows PowerShell techniques 12-3

Question and Answers


Question: Why is the location in which you store a user profile script important?

Answer: The location in which you store a user profile script determines whether Windows
PowerShell uses it for all users or just the current user. If the profile script is stored in $pshome,
then Windows PowerShell uses it for all users. If the profile script is stored in
$home\Documents\WindowsPowerShell, then Windows PowerShell uses it only for the
current user.

Demonstration: Creating a profile script


Demonstration Steps
1. On LON-CL1, on the taskbar, click File Explorer.

2. In File Explorer, in the navigation pane, under Quick Access, click Documents.
3. Click the Home tab, click New Folder, type WindowsPowerShell, and then press Enter.

4. Double-click WindowsPowerShell.
5. Click the Home tab, click New Item, and then click Text Document.

6. Clear the existing name, type Profile.ps1, and then press Enter.

7. In the Rename dialog box, click Yes.


8. Right-click Profile.ps1, and then click Edit.
9. In the Windows PowerShell ISE, type $servers=”LON-DC1”,”LON-SVR1”.

10. Click the File menu, and then click Save.

11. Close the Windows PowerShell ISE.


12. Click Start, type power, and then click Windows PowerShell.

13. To display the value of $servers, at the Windows PowerShell prompt, type the following command,
and then press Enter:

$servers

14. Close the Windows PowerShell prompt.


12-4 Automating Administration with Windows PowerShell

Lesson 2
Using advanced techniques
Contents:
Question and Answers 5
Resources 5
Demonstration: Using regular expressions 5
Demonstration: Using the format operator 7
Demonstration: Setting NTFS permissions 8
Using advanced Windows PowerShell techniques 12-5

Question and Answers


Question: If you run an external command at a Windows PowerShell prompt and get an unexpected
error, how can you try to resolve it?

Answer: Sometimes external commands use characters that Windows PowerShell tries to
interpret differently. To avoid this, when running an external command, use the stop parsing
symbol (--%) before the arguments.

Resources

The format operator

Additional Reading: For additional information on format strings, refer to “Formatting


Types in .NET” at https://aka.ms/jvyw6j.

Running external commands

Additional Reading: For additional information about the stop parsing symbol, refer to
“About Parsing” at https://aka.ms/vhxi7r.

Working with NTFS permissions

Additional Reading: For more information on permissions, refer to “NTFSSecurity Tutorial


1 – Getting, adding and removing permissions” at https://aka.ms/hbumre.
Additional Reading: For more information on NTFS inheritance, refer to “NTFSSecurity
Tutorial 2 – Managing NTFS Inheritance and Using Privileges” at https://aka.ms/th8i3x.

Demonstration: Using regular expressions


Demonstration Steps
1. On LON-CL1, click Start, type powersh, and then click Windows PowerShell.
2. To see matching of a substring, type the following command, and then press Enter:

"A large string" -match "large"

3. To see that a dot matches one character, type the following command, and then press Enter:

"LON-DC1" -match "LON-DC."

4. To see that a dot does not match zero characters, type the following command, and then press Enter:

"LON-DC" -match "LON-DC."

5. To see that a question mark matches one character, type the following command, and then press
Enter:

"LON-DC1" -match "LON-DC?"


12-6 Automating Administration with Windows PowerShell

6. To see that a question mark matches zero characters, type the following command, and then press
Enter:

"LON-DC" -match "LON-DC?"

7. To see that a plus matches one instance of the preceding character, type the following command, and
then press Enter:

"LON-DC1" -match "LON-DC+1"

8. To see that a plus matches multiple instances of the preceding character, type the following
command, and then press Enter:

"LON-DCCCC1" -match "LON-DC+1"

9. To see that a plus does not match zero instances of the preceding character, type the following
command, and then press Enter:

"LON-D1" -match "LON-DC+1"

10. To see that an asterisk matches one instance of the preceding character, type the following
command, and then press Enter:

"LON-DC1" -match "LON-DC*1"

11. To see that an asterisk matches multiple instances of the preceding character, type the following
command, and then press Enter:

"LON-DCCCC1" -match "LON-DC*1"

12. To see that an asterisk matches zero instances of the preceding character, type the following
command, and then press Enter:

"LON-D1" -match "LON-DC*1"

13. To see that “\w” matches word characters, type the following command, and then press Enter:

"LON-DC1" -match "LON-DC\w"

14. To see that “\s” matches space characters and not digits, type the following command, and then press
Enter:

"LON-DC1" -match "LON-DC\s"

15. To see that “\d” matches digit characters, type the following command, and then press Enter:

"LON-DC1" -match "LON-DC\d"

16. To see matching minimum and maximum instances of a character, type the following command, and
then press Enter:

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


Using advanced Windows PowerShell techniques 12-7

17. To see matching minimum and maximum instances of a character, type the following command, and
then press Enter:

"1-123-1" -match "\d{1,3}-\d{1,3}-\d{1,3}"

18. To see matching minimum and maximum instances of a character fail, type the following command,
and then press Enter:

"1-1234-1" -match "\d{1,3}-\d{1,3}-\d{1,3}"

19. To see matching of a substring without defining start and end, type the following command, and
then press Enter:

"1234" -match "\d{1,3}"

20. To see matching of a string with the start and end defined fail, type the following command, and
then press Enter:

"1234" -match "^\d{1,3}$"

21. Close the Windows PowerShell prompt.

Demonstration: Using the format operator


Demonstration Steps
1. On LON-CL1, click Start, type powersh, and then click Windows PowerShell.
2. To see index numbers for the format operator, type the following command, and then press Enter:

"File name: {0} File size: {1}" -f "Test.txt",20023.34587

3. To see index numbers for the format operator, type the following command, and then press Enter:

"File name: {1} File size: {0}" -f "Test.txt",20023.34587

4. To see alignment, type the following command, and then press Enter:

"File name: {0,-15} File size: {1,12}" -f "Test.txt",20023.34587

5. To see the fixed-point format string, type the following command, and then press Enter:

"File name: {0,-15} File size: {1,12:f2}" -f "Test.txt",20023.34587

6. To see the number format string, type the following command, and then press Enter:

"File name: {0,-15} File size: {1,12:n2}" -f "Test.txt",20023.34587

7. To see the currency format string, type the following command, and then press Enter:

"Expense name: {0,-15} Cost: {1,12:c}" -f ”Dinner”,53.25

8. To see a custom time format, type the following command, and then press Enter:

"{0,2:hh}:{0,2:mm}" -f (Get-Date)

9. Close the Windows PowerShell prompt.


12-8 Automating Administration with Windows PowerShell

Demonstration: Setting NTFS permissions


Demonstration Steps
1. On LON-CL1, click Start, type powersh, and then click Windows PowerShell.

2. To create a new folder, type the following command, and then press Enter:

New-Item C:\test -ItemType Directory

3. To put the ACL for the folder in $acl, type the following command, and then press Enter:

$acl = Get-Acl C:\test

4. To view the contents of $acl, type the following command, and then press Enter:

$acl

5. To view a summary of access rules, type the following command, and then press Enter:

$acl.AccessToString

6. To view detailed access rules, type the following command, and then press Enter:

$acl.Access

7. To view the properties and methods for an ACL, type the following command, and then press Enter:

$acl | Get-Member

8. To disable inheritance and clear inherited permissions, type the following command, and then press
Enter:

$acl.SetAccessRuleProtection($true,$false)

9. To create a new access rule for Administrators, type the following command, and then press Enter:

$rule = New-Object
System.Security.AccessControl.FileSystemAccessRule(“Administrators”,”FullControl”,
“ContainerInherit, ObjectInherit”, “None”, “Allow”)

10. To add the access rule to the ACL, type the following command, and then press Enter:

$acl.AddAccessRule($rule)

11. To apply the ACL to C:\Test, type the following command, and then press Enter:

Set-Acl C:\Test -AclObject $acl

12. To verify that the permissions were modified, type the following command, and then press Enter:

Get-Acl C:\Test | FL

13. Close the Windows PowerShell prompt.


Using advanced Windows PowerShell techniques 12-9

Module Review and Takeaways


Review Questions
Question: If you are using the format operator to display a number, how do you specify the number of
decimal places to include?

Answer: To specify the number of decimal places for a number or fixed-point format string, you
include an integer that specifies the number of decimal places. For example, n3 is a number with
three decimal places.
Question: Your organization has decided to log all use of Windows PowerShell on domain controllers.
How will you do this?

Answer: You should enable module logging for all modules on the domain controllers by using a
GPO. Module logging captures all Windows PowerShell commands that run and stores them in
the Windows PowerShell operational event log.
12-10 Automating Administration with Windows PowerShell

Lab Review Questions and Answers


Lab: Practicing advanced techniques
Question and Answers
Question: When you created the value for the -Path parameter while creating user accounts, is there a
way that you could have automatically identified the current domain?

Answer: Yes, you could have used the Get-ADDomain cmdlet to get the current domain. The
name of the domain is stored in the DistinguishedName attribute.
Question: When you use the format operator to align columns, how do you know how wide to make the
columns?

Answer: You need to select the column width based on the data you expect to display. If you
think that the data will only be five characters, then you can make the column just a little wider
than that.

S-ar putea să vă placă și