Anda di halaman 1dari 96

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

10962C
Advanced Automated Administration with
Windows PowerShell
Companion Content
ii Advanced Automated 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: 10962C

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


Creating advanced functions 1-1

Module 1
Creating advanced functions
Contents:
Lesson 1: Converting a command into an advanced function 2

Lesson 2: Creating a script module 4


Lesson 3: Defining parameter attributes and input validation 6

Lesson 4: Writing functions that accept pipeline input 10

Lesson 5: Producing complex function output 12


Lesson 6: Documenting functions by using comment-based Help 14

Lesson 7: Supporting –WhatIf and –Confirm 16

Module Review and Takeaways 18


Lab Review Questions and Answers 19
1-2 Advanced Automated Administration with Windows PowerShell

Lesson 1
Converting a command into an advanced function
Contents:
Demonstration: Creating an advanced function 3
Demonstration: Testing advanced functions 3
Creating advanced functions 1-3

Demonstration: Creating an advanced function


Demonstration Steps
1. Open E:\Allfiles\Mod01\Democode\Lesson01\Demo01\Step-01.ps1, and then run the script. The
command shown will query a Common Information Model (CIM) instance from the local computer.
You can demonstrate the command a second time by changing localhost to LON-
DC1.Adatum.com.

2. Open E:\Allfiles\Mod01\Democode\Lesson01\Demo01\Step-02.ps1, and then point out that the


localhost value can be parameterized so that the script can run against a different computer every
time.
3. Open E:\Allfiles\Mod01\Democode\Lesson01\Demo01\Step-03.ps1, and then show the Param()
block at the top of the script. In the block, point out the parameter named ComputerName. Explain
that inside the script, the parameter is basically a variable. That variable can be used instead of the
hard-coded localhost value.

4. Open E:\Allfiles\Mod01\Democode\Lesson01\Demo01\Step-04.ps1, and then show that the


[CmdletBinding()] attribute must be the first line of code inside the function, and the Param() block
must immediately follow. This attribute enables the additional features that make this function an
advanced function. Mention that running the script does not run the function. Students will learn how
to test the function next.

Demonstration: Testing advanced functions


Demonstration Steps
1. Open E:\Allfiles\Mod01\Democode\Lesson01\Demo02\Step-01.ps1, and then point out the
function’s name followed by its parameter. A test value is provided to the parameter.
2. After you run the script once, change localhost to lon-dc1.adatum.com and then run the script
again.

3. Point out that when you define a parameter, a dollar sign ($) precedes the parameter’s name because
inside the script, the parameter works as a variable. When you run the command, a dash precedes the
parameter name.
1-4 Advanced Automated Administration with Windows PowerShell

Lesson 2
Creating a script module
Contents:
Resources 5
Demonstration: Converting a script into a script module 5
Demonstration: Testing a script module 5
Demonstration: Adding verbose output 5
Creating advanced functions 1-5

Resources

Creating module manifests

Additional Reading: For more information regarding module manifest elements and a
sample manifest file, refer to “How to Write a PowerShell Module Manifest” at
https://aka.ms/kqz2nv.

Demonstration: Converting a script into a script module


Demonstration Steps
1. Open E:\Allfiles\Mod01\Democode\Lesson02\Demo01\Step-01.ps1. In the script file, remove any
commands outside the function. Point out that only the function is included in the script file.

2. Save the file in \Documents\WindowsPowerShell\Modules\DemoTools\DemoTools.psm1.


Create the folder structure if necessary.

Demonstration: Testing a script module


Demonstration Steps
1. Open E:\Allfiles\Mod01\Democode\Lesson02\Demo02\Step-01.ps1.
2. Run the script.

Demonstration: Adding verbose output


Demonstration Steps
1. Open E:\Allfiles\Mod01\Democode\Lesson02\Demo03\Step-01.ps1, and then run the script.
2. In the script, note the use of Write-Verbose. Double quotation marks (“ ”) are used around the
verbose message because the $ComputerName variable is included in the message. The shell will
replace the variable with its contents in the final output.

3. Save the file as \Documents\WindowsPowerShell\Modules\DemoTools\DemoTools.psm1,


replacing the existing file.

4. In Windows PowerShell ISE, run the following command:

Import-Module –Name DemoTools -Force

5. In the same Windows PowerShell ISE window, open


E:\Allfiles\Mod01\Democode\Lesson02\Demo03\Step-02.ps1, and then run the script. Point out
that you can easily suppress or show verbose output by omitting or including the –Verbose
parameter.
1-6 Advanced Automated Administration with Windows PowerShell

Lesson 3
Defining parameter attributes and input validation
Contents:
Demonstration: Defining parameter attributes 7
Demonstration: Defining parameter input validation 7
Demonstration: Enumerating objects by using the ForEach construct 8
Creating advanced functions 1-7

Demonstration: Defining parameter attributes


Demonstration Steps
1. Open E:\Allfiles\Mod01\Democode\Lesson03\Demo01\Step-01.ps1. Review the current script
module. Point out that the script module has a single parameter, -ComputerName. An extra line is
added where the parameter attributes will be put.

2. Open E:\Allfiles\Mod01\Democode\Lesson03\Demo01\Step-02.ps1. Point out that the –


ComputerName parameter has been defined as mandatory. The [Parameter()] attribute is usually
added first.
3. Open E:\Allfiles\Mod01\Democode\Lesson03\Demo01\Step-03.ps1. Point out the Help message
added to the parameter. Remember that the Help message usually shows only when the user asks for
it, when the shell is prompting the user for a value. The Help message should usually be a short, one-
line description. You can provide more extensive documentation elsewhere, which will be covered
later in this module.

4. Open E:\Allfiles\Mod01\Democode\Lesson03\Demo01\Step-04.ps1. Point out the –HostName


alias added to the parameter. Mention that parameter names are not case-sensitive. However, if a
user uses tab completion, the parameter name will be capitalized the same way that it is defined in
the script.

5. Open E:\Allfiles\Mod01\Democode\Lesson03\Demo01\Step-05.ps1. Point out the syntax for


defining a second parameter. Point out that the second parameter name is followed by a comma. The
comma tells the shell that another parameter definition follows. The second parameter has its own
[Parameter()] attribute, data type, and parameter name.

6. Open E:\Allfiles\Mod01\Democode\Lesson03\Demo01\Step-06.ps1. Save the file as


\Documents\WindowsPowerShell\Modules\DemoTools\DemoTools.psm1.

7. In Windows PowerShell ISE, run the following command:

Import-Module –Name DemoTools -Force

8. In the same Windows PowerShell ISE window, open


E:\Allfiles\Mod01\Democode\Lesson03\Demo01\Step-07.ps1. Select the first Get-
CorpCompSysInfo command, and then run the selection. Point out that using –HostName is the
same as using –ComputerName. Select the second Get-CorpCompSysInfo command, and then run
the selection. When prompted to provide the value of the –ComputerName parameter, type the
following:

!?

9. Point out the Help message.

10. Stop the execution of the script.

Demonstration: Defining parameter input validation


Demonstration Steps
1. Open E:\Allfiles\Mod01\Democode\Lesson03\Demo02\Step-01.ps1. Point out the regular
expression pattern validation of the parameter. Explain that the regular expression provided requires
computer names that begin with “LON-“ and then have two or three characters followed by one or
two digits.
Save the script as \Documents\WindowsPowerShell\Modules\DemoTools\DemoTools.psm1.

2. In Windows PowerShell ISE, run the following command:


1-8 Advanced Automated Administration with Windows PowerShell

Import-Module –Name DemoTools -Force

3. In the same Windows PowerShell ISE window, open


E:\Allfiles\Mod01\Democode\Lesson03\Demo02\Step-02.ps1. Select the first command, and
then run the selection. Review the error message carefully after you run the first command. It
describes the problem in detail. Select the second command, and then run the selection. Ensure that
it completes successfully.

Demonstration: Enumerating objects by using the ForEach construct


Demonstration Steps
1. Open E:\Allfiles\Mod01\Democode\Lesson03\Demo03\Step-01.ps1. Review the example script
module. Point out the additional lines that were added where the new code will be entered.

2. Open E:\Allfiles\Mod01\Democode\Lesson03\Demo03\Step-02.ps1. Point out the


$ComputerName parameter that accepts multiple values. Changing the parameter data type from
[string] to [string[]] means that it will only accept a collection. If the command runs with only one
computer name, the shell will implicitly create a collection of one item and then pass that collection
to the parameter.
3. Open E:\Allfiles\Mod01\Democode\Lesson03\Demo03\Step-03.ps1. Point out the ForEach
construct that enumerates the computer names. The ForEach construct uses $ComputerName as its
second argument because that is the variable that will contain one or more items. The function does
not use $Computers, a plural noun, because –ComputerName is the consistent parameter name, not
–Computers. Windows PowerShell parameter names are usually not plural even when they accept
multiple items.
4. Open E:\Allfiles\Mod01\Democode\Lesson03\Demo03\Step-04.ps1. Point out that the
enumerator variable was changed to $computer. Because the commands are now in a ForEach
construct, they must be changed to use the variable that will contain only one computer name at a
time.

5. Save the revised script module to


\Documents\WindowsPowerShell\Modules\DemoTools\DemoTools.psm1.

6. In Windows PowerShell ISE, run the following command:

Import-Module –Name DemoTools -Force.

7. In the same Windows PowerShell ISE window, open


E:\Allfiles\Mod01\Democode\Lesson03\Demo03\Step-05.ps1. Run the command with multiple
computer names. Point out that multiple values are separated by using a comma.

8. Open E:\Allfiles\Mod01\Democode\Lesson03\Demo03\Step-06.ps1. Point out the new function


that retrieves disk information from one or more computers. This function follows the same coding
pattern as the previous example. However, this function retrieves disk information. That means each
computer might return more than one piece of information. A second ForEach construct, nested
inside the first, enumerates the disk objects.

Press F5 to run this script. You do not have to save it as a script module.
Creating advanced functions 1-9

9. Open E:\Allfiles\Mod01\Democode\Lesson03\Demo03\Step-07.ps1. Review the example that


uses different variable names. You can run this script by pressing F5.

This script demonstrates that although there are conventions used for naming variables in a ForEach
construct, those conventions are for human understanding. The shell will run this script and produce
the same results as the previous example even though the variable names are nonsensical from a
human perspective.
1-10 Advanced Automated Administration with Windows PowerShell

Lesson 4
Writing functions that accept pipeline input
Contents:
Demonstration: Changing a function to accept and use pipeline input 11
Creating advanced functions 1-11

Demonstration: Changing a function to accept and use pipeline input


Demonstration Steps
1. Open E:\Allfiles\Mod01\Democode\Lesson04\Demo01\Step-01.ps1. The starting point shows a
function that does not accept pipeline input.

2. Open E:\Allfiles\Mod01\Democode\Lesson04\Demo01\Step-02.ps1. Point out that the –


ComputerName parameter is defined so that it accepts pipeline input by using both ByValue and
ByPropertyName.

3. Open E:\Allfiles\Mod01\Democode\Lesson04\Demo01\Step-03.ps1. Point out that the BEGIN


and END blocks are not included. The content of the function is wrapped in a PROCESS block. The
ForEach construct is still required.

4. Save this file as \Documents\WindowsPowerShell\Modules\DemoTools\DemoTools.psm1.

5. In Windows PowerShell ISE, run the following command:

Import-Module –Name DemoTools –Force

6. Open E:\Allfiles\Mod01\Democode\Lesson04\Demo01\Step-04.ps1. The different commands


illustrate using the function without using pipeline input and by using ByValue and ByPropertyName.
The last example creates a .csv file (comma-separated file) that includes a ComputerName column so
that the Import-CSV command can produce an object having a ComputerName property. Select
each command in the file and run the selection.
1-12 Advanced Automated Administration with Windows PowerShell

Lesson 5
Producing complex function output
Contents:
Demonstration: Creating and producing custom objects 13
Creating advanced functions 1-13

Demonstration: Creating and producing custom objects


Demonstration Steps
1. Open E:\Allfiles\Mod01\Democode\Lesson05\Demo01\Step-01.ps1. Point out that this is the
same function from the previous lesson.

2. Open E:\Allfiles\Mod01\Democode\Lesson05\Demo01\Step-02.ps1. Point out that you plan to


query more than one object in the function. Because you do not want two objects going to the
pipeline, you save each into a variable. You can then use the variables to combine the information
that you want into a single output object.
3. Open E:\Allfiles\Mod01\Democode\Lesson05\Demo01\Step-03.ps1. Point out that the second
command’s output is also saved to a variable.

4. Open E:\Allfiles\Mod01\Democode\Lesson05\Demo01\Step-04.ps1. Point out that the


semicolons are not needed, but using them is a good practice. If the hash table were defined on a
single line, the semicolons would be required.

5. Open E:\Allfiles\Mod01\Democode\Lesson05\Demo01\Step-05.ps1. This specific example would


not require the output object to be saved in a variable. However, there are times when you will want
to make changes to the object before producing it. The practice of always saving the object in a
variable makes the function easier to extend in the future, if it is necessary.
6. Open E:\Allfiles\Mod01\Democode\Lesson05\Demo01\Step-06.ps1. Press F5 to run the script.
Point out that the order of the properties in the output differs from their order in the script. The shell
uses a memory-efficient hash table by default, and it does not preserve property order.
7. Open E:\Allfiles\Mod01\Democode\Lesson05\Demo01\Step-07.ps1. This example demonstrates
that the output object can pipe to other shell commands. In this example, Select-Object is used to
select all the object’s properties. The order of those properties is retained in the output because that
is part of the way Select-Object is designed to work.
8. Open E:\Allfiles\Mod01\Democode\Lesson05\Demo01\Step-08.ps1. Ordered hash tables
preserve the order of the properties, but they are less memory-efficient. Additionally, remember that
the command should not address the attractiveness of the output. The output can pipe to other
commands, such as Select-Object or Format-Table, to display the output in a more attractive form.

9. Open E:\Allfiles\Mod01\Democode\Lesson05\Demo01\Step-09.ps1.

10. Save the file as \Documents\WindowsPowerShell\Modules\DemoTools\DemoTools.psm1.

11. In Windows PowerShell ISE, run the following command:

Import-Module –Name DemoTools –Force

12. Then, in the same Windows PowerShell ISE window, run the following code:

Get-CorpCompSysInfo –ComputerName LON-DC1,LON-SVR1


1-14 Advanced Automated Administration with Windows PowerShell

Lesson 6
Documenting functions by using comment-based
Help
Contents:
Demonstration: Adding comment-based Help to a function 15
Creating advanced functions 1-15

Demonstration: Adding comment-based Help to a function


Demonstration Steps
1. Open E:\Allfiles\Mod01\Democode\Lesson06\Demo01\Step-01.ps1. Point out that this is the
same function as in the previous demonstration.

2. Open E:\Allfiles\Mod01\Democode\Lesson06\Demo01\Step-02.ps1. Point out the formatting of


the .PARAMETER and .EXAMPLE sections. Additionally, point out the location of the comment-
based Help block.

3. Save the file as \Documents\WindowsPowerShell\Modules\DemoTools\DemoTools.psm1.

4. In Windows PowerShell ISE, run the following command:

Import-Module –Name DemoTools –Force

5. Open E:\Allfiles\Mod01\Democode\Lesson06\Demo01\Step-03.ps1. Select each command, and


then run the selection. The examples show the brief (default) Help, the full Help, and the full Help in a
floating window.
1-16 Advanced Automated Administration with Windows PowerShell

Lesson 7
Supporting –WhatIf and –Confirm
Contents:
Demonstration: Declaring support for –WhatIf and –Confirm 17
Demonstration: Adding support for -WhatIf and -Confirm 17
Creating advanced functions 1-17

Demonstration: Declaring support for –WhatIf and –Confirm


Demonstration Steps
1. Open E:\Allfiles\Mod01\Democode\Lesson07\Demo01\Step-01.ps1. This starting point includes
a brand-new function, Set-CorpComputerState. Functions that use the verb Get in their names
should not be making any changes, and therefore, it makes no sense to add ShouldProcess support to
the Get-CorpCompSysInfo function that you have been using in demonstrations up to this point.
Instead, this new function uses the verb Set, implying that it will make a change of some kind.

2. Note that the command accepts three parameters. Describe these parameters to students, and then
review the function code to help students understand what the function does.
3. This example uses the Switch and If constructs. The next topics will explain them. Additionally, this is
the first example in which a BEGIN script block is used. Remind students that the BEGIN block runs
first.

4. Open E:\Allfiles\Mod01\Democode\Lesson07\Demo01\Step-02.ps1. Point out that the


[CmdletBinding()] attribute was modified. Declaring support does not implement that support, so
this example is the first of two steps that you must follow to provide full support for –WhatIf and –
Confirm.

Demonstration: Adding support for -WhatIf and -Confirm


Demonstration Steps
1. Open E:\Allfiles\Mod01\Democode\Lesson07\Demo02\Step-01.ps1. When you implement
support for ShouldProcess, it is important to find the smallest number of commands that actually
change the system. In this example, only the Win32Shutdown() method modifies the system state.
However, the Get-WmiObject command can be time-consuming to run, so there is no point in
running it if the user does not want to continue. Therefore, both commands are included in the If
construct that runs the ShouldProcess() method.

2. Save the script as \Documents\WindowsPowerShell\Modules\DemoTools\DemoTools.psm1.


3. In Windows PowerShell ISE, run the following command:

Import-Module –Name DemoTools –Force

4. Open E:\Allfiles\Mod01\Democode\Lesson07\Demo02\Step-02.ps1. Point out that –Confirm is


not specified, but the command will run as if –Confirm was used. That is because the ConfirmImpact
of the command was specified as High.

5. Run the command included in the script. If you answer Yes to the confirmation prompt, ensure that
you use Hyper-V Manager to restart 10962C-LON-DC1 after it shuts down.
1-18 Advanced Automated Administration with Windows PowerShell

Module Review and Takeaways


Best Practice
Focus on function formatting. Neatly formatted scripts are easier to read, understand, and maintain.

Review Question
Question: What different kinds of tools or commands do you think that you might write in the future?

Answer: Specific answers will vary. However, Windows PowerShell has three broad categories of
commands:
• Commands that retrieve information or create input for other commands. These commands
often have names that include verbs like Get, Import, and ConvertFrom.

• Commands that perform work or retrieve information. These commands often have names
that include verbs such as Get, Set, Remove, and New.

• Commands that accept input from other commands and produce formatting for a specific
purpose. These commands often have names that include verbs like Format, Out, Export,
and ConvertTo.
Creating advanced functions 1-19

Lab Review Questions and Answers


Lab A: Converting a command into an advanced function
Question and Answers
Question: Why did you use Get-CorpOSInfo as the command name?

Answer: The command name follows Windows PowerShell command-line interface standards.
The command name consists of a standard shell verb, Get, followed by a hyphen. The second
part of the command name includes a prefix, Corp, that helps make sure that the command
name will be unique. In your environment, you might include an abbreviated form of your
organization name as a prefix.

Lab B: Creating a script module

Question and Answers


Question: What are the advantages of a script module over a regular script?

Answer: There are several advantages:


• When script modules are saved in the correct location, the shell can discover commands in a
script module, helping users find those commands more easily.

• Script modules can contain multiple commands that load and unload as a single unit.
• Script modules can distribute to other users by copying the script module file.

• No special syntax is necessary to run the commands that are in a script module; they work
exactly like native shell cmdlets.

Lab C: Defining parameter attributes and input validation

Question and Answers


Question: When might you use a default parameter value instead of making the parameter mandatory?

Answer: When a parameter is usually given a specific value, you can make the command easier
to use by defining that value as a default for the parameter. However, if a parameter always
requires a value but no specific value is usually used, it makes more sense to mark the parameter
as mandatory.

Lab D: Writing functions that use multiple objects

Question and Answers


Question: Why did the E:\Allfiles\Mod01\Labfiles\Lab D – Answer.ps1 script indent the code that was
inside the ForEach constructs?

Answer: It is a best practice to indent code that is inside a construct. Indentation helps you
visually identify the code that is part of the construct, and it helps make scripts easier to read,
understand, and troubleshoot.
1-20 Advanced Automated Administration with Windows PowerShell

Question: If it is a best practice to use plural names for variables that contain collections, why did the lab
use $ComputerName to contain one or more values?

Answer: Using plural names for collections is a good practice, but when naming parameters, a
more important practice is to notice the usual Windows PowerShell naming patterns. Existing
cmdlets do not use –Computers as a parameter name. Instead, they use –ComputerName.
Therefore, $ComputerName was used in the lab script.

Lab E: Writing functions that accept pipeline input

Question and Answers


Question: What parameters should accept pipeline input?

Answer: You must consider how your function will be used and what kind of input it will accept.
For example, if you plan to run Get-ADComputer to produce computer objects, you might want
to define your function to accept that kind of object from the pipeline. Doing this would enable
the function to target the computers that are represented by the computer objects.

Lab F: Producing complex function output

Question and Answers


Question: What would you do if you wanted the output of a function to be formatted differently or to
use specific units of measure?
Answer: Command output is usually not concerned with how output will be used or displayed.
Specific commands in the shell are designed to accept object input and produce a formatted
display. For example, both Select-Object and Format-Table can accept any object from the
pipeline and arrange the output for a specific display purpose. Windows PowerShell views can
also provide specific default formatting, such as what displays when you run Get-Process.

Lab G: Documenting functions by using comment-based Help

Question and Answers


Question: When displaying the full Help for your command, Windows PowerShell displays additional
information about the –ComputerName parameter. For example, it listed the fact that the parameter is
required instead of being optional. Where did that information come from?

Answer: Windows PowerShell reads the parameter attributes for some information instead of
finding that information in the comment-based Help. Because the –ComputerName parameter is
defined as Mandatory, the shell could reflect that information in the displayed Help.

Lab H: Supporting –WhatIf and –Confirm

Question and Answers


Question: Why would you implement ShouldProcess only around the fewest number of possible
commands?

Answer: Your ShouldProcess If construct should include the least number of commands to make
sure that your command makes no actual changes if it runs by using –WhatIf. Other commands
in your function should run so that the function behaves as closely as possible to normal without
making any actual changes.
Using Microsoft .NET Framework and REST API in Windows PowerShell 2-1

Module 2
Using Microsoft .NET Framework and REST API in Windows
PowerShell
Contents:
Lesson 1: Using .NET Framework in Windows PowerShell 2
Lesson 2: Using REST API in Windows PowerShell 4

Module Review and Takeaways 7

Lab Review Questions and Answers 8


2-2 Advanced Automated Administration with Windows PowerShell

Lesson 1
Using .NET Framework in Windows PowerShell
Contents:
Question and Answers 3
Demonstration: Using static .NET Framework class members 3
Demonstration: Instantiating classes and using instance members 3
Using Microsoft .NET Framework and REST API in Windows PowerShell 2-3

Question and Answers


Question: Why would you use .NET Framework classes instead of a Windows PowerShell command?

Answer: Usually, you would use a .NET Framework class only when you cannot find a Windows
PowerShell command to accomplish your task and a .NET Framework class exists that meets your
needs. Internally, Windows PowerShell commands use .NET Framework classes, but the structure
of the commands provide a more consistent and documented experience for administrators, than
by using the class directly.

Demonstration: Using static .NET Framework class members


Demonstration Steps
1. Open E:\Allfiles\Mod02\Democode\Using_Static_NET_Framework_Class_Members.ps1.

2. Follow instructions in the file.

Demonstration: Instantiating classes and using instance members


Demonstration Steps
1. Open E:\Allfiles\Mod02\Democode\Instantiating_Classes_and_Using_Instance_Members.ps1.

2. Follow instructions in the file.


2-4 Advanced Automated Administration with Windows PowerShell

Lesson 2
Using REST API in Windows PowerShell
Contents:
Question and Answers 5
Resources 5
Demonstration: Invoking REST API methods by using Windows PowerShell 5
Using Microsoft .NET Framework and REST API in Windows PowerShell 2-5

Question and Answers


Question: When would you consider using REST API methods from Windows PowerShell?

Answer: Writing scripts that invoke REST API methods tends to be relatively complex when
compared to typical Windows PowerShell scripts that rely on standard cmdlets or even .NET
Framework classes. In general, the primary reason for resorting to using the REST API is to
facilitate communication with remote systems that are not accessible directly via Windows
PowerShell, but offer support for REST API.

Resources
The REST API documentation

Additional Reading: For more information on API Explorer, refer to “API Explorer” at
https://aka.ms/lmb0ho.

Additional Reading:

• Microsoft Azure REST API Reference - https://aka.ms/yk8kyp


• Microsoft Intune REST API reference - https://aka.ms/dwurw5

• REST API Overview for Visual Studio Team Services and Team Foundation Server -
https://aka.ms/a9iofb

REST API Syntax

Additional Reading: For more information, refer to the “Components of a REST API
request/response” section of https://aka.ms/vmiy1i.

Invoking REST API methods by using Windows PowerShell

Additional Reading: For more information on the Invoke-RestMethod command, refer


to “Invoke-RestMethod” at https://aka.ms/hmvkjb.

Demonstration: Invoking REST API methods by using Windows PowerShell


Demonstration Steps
1. From Windows PowerShell ISE on LON-CL1, open E:\Allfiles\Mod02\DemoCode\Using_Invoke-
RestMethod.ps1.

2. Review the script and describe what it does. Point out that the function Get-AdminApiHeaders
generates the REST API request header for the script that follows. Explain that the purpose of the
script is to enumerate websites and web application pools on LON-SVR1 by using the IIS
Administration API installed on that server.

3. Run the script and verify that it returns the expected results, which should consist of the REST API
header followed by the JSON representation of the Default Web Site and DefaultAppPool on LON-
SVR1.
4. Connect to LON-SVR1, and then on LON-SVR1, start Microsoft Internet Explorer, and browse to
https://localhost:55539.
2-6 Advanced Automated Administration with Windows PowerShell

5. From Internet Explorer, on the Connect page, click Get Access Token.

6. On the Access Keys page, click Create Access Key.

7. In the Access Key Purpose text box, type demo, click 1 DAY, and then click Create it.

8. On the Access Token page, select the newly created key, copy it to the clipboard, and then click Got
it.

9. In Internet Explorer, click API EXPLORER. In the Access Token text box, paste the newly generated
key, and then click Connect.
10. Click the /api/webserver link.

11. Click the /api/webserver/websites link. Point out to students that by using the API Explorer
interface, you can identify the parameters of GET, POST, PATCH, PUT, HEAD and DELETE REST API
methods.

Explain that the GET method is executed by default, and point out that the output that API Explorer
generates matches the output of the Windows PowerShell script that you ran.

12. Switch to LON-CL1, start Internet Explorer, and then browse to https://docs.microsoft.com/en-
us/iis-administration/api/sites.
13. Review the content of the Web Site Resource page, and point out that it documents the web site
REST API resource and a number of methods it supports, including the GET method.
Using Microsoft .NET Framework and REST API in Windows PowerShell 2-7

Module Review and Takeaways


Best Practice
When possible, use Windows PowerShell commands to accomplish administrative tasks instead of using
the corresponding .NET Framework classes or REST API methods. Commands are often easier for other
shell users to understand because of their naming conventions and built-in documentation.

Review Question
Question: Where would you go to start looking for a .NET Framework class that can accomplish a specific
task?

Answer: There is no one location. There are tens of thousands of .NET Framework classes. Those
produced by companies other than Microsoft might not be documented, or the documentation
might not be readily available. An Internet search engine or the MSDN Library search feature can
be the best way to start looking for Microsoft-provided classes that perform specific tasks.

Real-world Issues and Scenarios


Scripts that use .NET Framework classes and REST API methods can be quite complex. If you need to
resort to referencing the .NET Framework classes or REST API methods more extensively than via a simple
Windows PowerShell script, consider using a solution such as Microsoft Visual Studio and a language such
as Visual Basic or C#. Those options provide a better .NET Framework and REST API programming
experience than Windows PowerShell.
2-8 Advanced Automated Administration with Windows PowerShell

Lab Review Questions and Answers


Lab A: Using .NET Framework in Windows PowerShell
Question and Answers
Question: How can you tell the difference between a static member and a member that must be used
from an instance?

Answer: In the MSDN Library documentation, static members have a yellow S icon next to them.
In addition, classes that consist entirely of static members are referred to as static classes in their
documentation.

Lab B: Using REST API in Windows PowerShell to manage IIS websites


Question and Answers
Question: What was the purpose of the auxiliary function included in the script
E:\Allfiles\Mod02\Labfiles\Lab B – Starting Point.ps1?

Answer: The function generates the header, which each of the subsequent Invoke-RestMethod
commands references via the –Headers parameter. In general, the header contains metadata
describing the request that you submit to the REST API endpoint. In this particular case, the
header facilitates access token-based communication between LON-CL1 and LON-SVR1.

Question: What are your options when identifying the proper syntax of the methods that you can use to
interact with the IIS Administration REST API?

Answer: You can refer to the online documentation available at https://aka.ms/j263qk.


In addition, you can use the API Explorer, which provides web-based interface to the REST API via
http://localhost:55539 on any server that has the IIS Administration API component installed.
Writing controller scripts 3-1

Module 3
Writing controller scripts
Contents:
Lesson 1: Understanding controller scripts 2

Lesson 2: Writing controller scripts that show a user interface 4


Lesson 3: Writing controller scripts that produce reports 7

Module Review and Takeaways 11

Lab Review Questions and Answers 12


3-2 Advanced Automated Administration with Windows PowerShell

Lesson 1
Understanding controller scripts
Contents:
Question and Answers 3
Writing controller scripts 3-3

Question and Answers


Question: Why should you avoid writing a function that returns formatted data such as returning disk
usage information in gigabytes (GBs) instead of bytes?

Answer: Tools are meant to be usable in as many situations as possible. By providing the lowest
level of data possible, you can make sure that the tool will help meet future needs that you might
not even anticipate. When you use the tool in a controller, the controller can provide additional
logic to format the data for that specific purpose.
3-4 Advanced Automated Administration with Windows PowerShell

Lesson 2
Writing controller scripts that show a user interface
Contents:
Question and Answers 5
Demonstration: Writing a text-based user menu 5
Writing controller scripts 3-5

Question and Answers


Question: Which of the following commands allow you to generate output with custom foreground and
background colors?

( ) Write-Host

( ) Write-Information

( ) Out-Null

( ) Write-Progress

( ) Clear-Host

Answer:
(√) Write-Host

( ) Write-Information

( ) Out-Null
( ) Write-Progress

( ) Clear-Host

Feedback
One of the features that Write-Host offers is the ability to generate output with custom
foreground and background colors. This functionality is not available when using Write-
Information. Out-Null suppresses output. Write-Progress allows you to display a progress bar
representing the status of the running script. Clear-Host clears currently displayed console
output.

Demonstration: Writing a text-based user menu


Demonstration Steps
1. Open the E:\Allfiles\Mod03\Democode\Lesson02\Demo01\Step-01.ps1 file. The functions in this
script are basically unchanged from Module 1, “Creating Advanced Functions.”

2. Save this file as \Documents\WindowsPowerShell\Modules\DemoTools\DemoTools.psm1.


Create the folder structure if necessary.

3. From the Windows PowerShell ISE console pane, run:

Import-Module –Name DemoTools -Force

4. Open the E:\Allfiles\Mod03\Democode\Lesson02\Demo01\Step-02.ps1 file.

If you prefer to use a Windows PowerShell–style name for this controller script, it might be Show-
SupportMenu.ps1. The verb Show implies that output will be displayed directly to the screen. In this
situation, the output is the menu.

Notice that the \n escape sequence is used inside double quotation marks. This sequence adds a
blank line to the output.

Also notice that some options use Write-Host to display additional instructions to the user. The tools
are run without parameters. However, because each tool has certain mandatory parameters, the tools
will provide their own prompts for values.

5. Run the script. When prompted for the computer name, enter either LON-DC1 or LON-SVR1. When
prompted for the computer state, you can specify PowerOff, Shutdown, Restart, or Logoff. After
you provide the value you are prompted for, press the Enter key twice.
3-6 Advanced Automated Administration with Windows PowerShell

If you receive errors concerning the Get-CorpCompSysInfo or Set-CorpComputerState cmdlets


when you run the script, ensure that you have saved the file
E:\Allfiles\Mod03\Democode\Lesson02\Demo01\Step-01.ps1 correctly as
…\Documents\WindowsPowerShell\Modules\DemoTools\DemoTools.psm1.

6. If you receive RPC errors when running the Set-CorpComputerState cmdlet, run the following
Windows PowerShell commands on LON-SVR1 to open the required firewalls. You can sign in by
using the credentials Adatum\Administrator and the password Pa55w.rd.

Enable-NetFirewallRule –DisplayName “File and Printer Sharing (Spooler Service*)”


Enable-NetFirewallRule –DisplayName “File and Printer Sharing (Virtual Machine
Monitoring (RPC)*)”

If you want to check connectivity by using ping, you also need to open the echo request firewall rules
as shown in the following example.

Enable-NetFirewallRule –DisplayName “File and Printer Sharing (Echo Request*)”

Also, when running the Set-CorpComputerState cmdlet in the DemoTools module, you might
notice that the Logoff state works as expected but the Restart, Poweroff, and Shutdown states do
not. No errors are reported, and you are just returned to the menu options. This is as expected, and it
is related to how the Win32_Shutdown works and the need to force those states.
7. If you go to the controller script that you opened earlier,

E:\Allfiles\Mod03\Democode\Lesson02\Demo01\Step-02.ps1, then go to line 28 and add the –


Verbose switch option, highlight the command and press F8 to just run that command as shown in
the following example:

Set-CorpComputerState -Verbose

8. Try all four state options against LON-SVR1, and note that the value of 0 is returned for success and
1191 for not having been successfully run.
9. After the command finishes running, note the presence of the -Force switch in the Set-
CorpComputerState function in DemoTools.psm1, and then again return to Line 28 in your
controller script file, E:\Allfiles\Mod03\Democode\Lesson02\Demo01\Step-02.ps1, add the –
Force switch, highlight the command, and press F8 to run that command as shown in the following
example:

Set-CorpComputerState –Verbose -Force

Note the return values for each option against LON-SVR1, how the LON-SVR1 virtual machines
responds, and that all the four options, Logoff, Shutdown, Restart, and PowerOff now run
successfully, when the -Force switch is used.

Also, if you are editing the module file, open a new console to run the cmdlet to ensure that the
module gets updated successfully.
Finally, if you get any other errors, you also need to ensure that the script is being run with the
appropriate elevated permissions.
Writing controller scripts 3-7

Lesson 3
Writing controller scripts that produce reports
Contents:
Question and Answers 8
Demonstration: How to convert command output into an HTML fragment 8
Demonstration: How to combine HTML fragments into an HTML page 9
Demonstration: How to add basic formatting to an HTML page 9
Demonstration: How to create controller scripts that produce
multisection HTML reports 9
3-8 Advanced Automated Administration with Windows PowerShell

Question and Answers


Question:

You want to create reports containing tables with custom formatted cells. What should you do?
( ) Use ConvertTo-Html with the -Head parameter

( ) Use Convert-to-Html with the CssUri parameter

( ) Use ConvertTo-Html with the -PostContent parameter


( ) Use ConvertTo-Html with the -PreContent parameter

( ) Use an open-source third-party module EnhancedHTML2

Answer:
( ) Use ConvertTo-Html with the -Head parameter

( ) Use Convert-to-Html with the CssUri parameter

( ) Use ConvertTo-Html with the -PostContent parameter


( ) Use ConvertTo-Html with the -PreContent parameter

(√) Use an open-source third-party module EnhancedHTML2


Feedback
The built-in ConvertTo-Html command enables only the basic HTML formatting capabilities.
You can create reports that have more detailed formatting, including formatting of individual
table cells by using an open-source third-party module called EnhancedHTML2. You can
download the module and instructions for using it from PowerShell.org. The -PreContent and -
PostContent parameters allow you to add custom text before and after <TABLE> tags. Using -
CssUri parameter requires having a CSS file. The Head parameter specifies the content of the
<HEAD> tag.

Demonstration: How to convert command output into an HTML fragment


Demonstration Steps
1. Open the E:\Allfiles\Mod03\Democode\Lesson03\Demo01\Step-01.ps1 file.

2. Review the functions that will be used.

3. Save this file as \Documents\WindowsPowerShell\Modules\DemoTools\DemoTools.psm1,


overwriting any existing file.

4. From the Windows PowerShell ISE console pane, run:

Import-Module –Name DemoTools -Force

5. Open the E:\Allfiles\Mod03\Democode\Lesson03\Demo01\Step-02.ps1 file.

6. Run commands in the file to convert output of Get-CorpCompSysInfo and Get-Process to HTML
fragments.
Notice that the system information is converted to a list because of the –As List parameter of
ConvertTo-Html. Also notice that specific properties can be selected, if you want. The fragments are
saved in variables for later use. You do not have to run this script at this point.
Writing controller scripts 3-9

Demonstration: How to combine HTML fragments into an HTML page


Demonstration Steps
1. Open the E:\Allfiles\Mod03\Democode\Lesson03\Demo02\Step-01.ps1 file.

Notice that an <h1> HTML header is used as the first fragment, giving the report an overall header.

2. Run the script, and then use Internet Explorer to open the C:\LON-DC1.html file.

Demonstration: How to add basic formatting to an HTML page


Demonstration Steps
1. Open the E:\Allfiles\Mod03\Democode\Lesson03\Demo03\Step-01.ps1 file. This is the same
script as in the previous demonstration.

2. Open the file E:\Allfiles\Mod03\Democode\Lesson03\Demo03\Step-02.ps1


A very simple <style> section is defined inside a here-string. This section includes basic formatting for
the HTML page and for table headers. Notice that the cascading style sheet (CSS) instructions are
saved in a variable, $style, and that the variable is included as the value for the –Head parameter of
ConvertTo-Html.

3. Run this script, and then use Internet Explorer to open the resulting c:\lon-dc1.html file. Note the
differences in background color and font in comparison with the previous file output.

In the lab, students will run Get-AdatumStyleSheet, to produce a similar <style> section.

Demonstration: How to create controller scripts that produce multisection


HTML reports
Demonstration Steps
1. Open the E:\Allfiles\Mod03\Democode\Lesson03\Demo04\Step-01.ps1 file.
Notice that this script resembles an advanced function. It has a parameter block, uses cmdlet binding,
and has a ForEach construct to enumerate computer names. It does not have a function keyword.
You will be able to run this script by providing computer names to it.

2. Open the E:\Allfiles\Mod03\Democode\Lesson03\Demo04\Step-02.ps1 file.

Notice that the script can accept multiple computer names. For each computer, the script produces
two HTML fragments. You can view the fragments for each computer by typing $frag1 and $frag2
after the command is complete. Each fragment has a list or table layout and a section header.

3. Run the script by pressing F5. When prompted for the computer name, specify LON-SVR1 and then
press Enter twice.

If you received an error indicating that Service Control Manager is not accessible on LON-SVR1, run
the following command on LON-SVR1 to open the relevant firewall.

Enable-NetFirewallRule –DisplayName “Remote Service Management (NP*)”

4. Open the E:\Allfiles\Mod03\Democode\Lesson03\Demo04\Step-03.ps1 file.


5. Run the script by pressing F5. When prompted for the computer name, specify LON-SVR1.

The script includes the Get-AdatumStyleSheet command that produces a company-standard CSS
style section. This embeds the style sheet into the <head> of the final HTML report. Doing this makes
the final file completely stand-alone. Using a CSS that comes from a centrally maintained function
helps provide consistency across reports.
3-10 Advanced Automated Administration with Windows PowerShell

6. Open the E:\Allfiles\Mod03\Democode\Lesson03\Demo04\Step-04.ps1 file.

Note that a new parameter was added that will enable you to specify an output folder for your report
files.
7. Open the E:\Allfiles\Mod03\Democode\Lesson03\Demo04\Step-05.ps1 file.

A BEGIN block was added that tests whether the folder path already exists. If it does not, the folder is
created. If the folder creation fails, –ErrorAction Stop will cause the script to fail and display an error
message. This approach makes sure that the script has a valid location where output files can be
saved.

8. Open the E:\Allfiles\Mod03\Democode\Lesson03\Demo04\Step-06.ps1 file.


The script includes Join-Path, which enables you to specify a path and a file name. The cmdlet makes
sure that the correct number of path separators (slashes) appear between each portion of the path.
Notice that a variable inside double quotation marks is used to create the output file name. A file will
be created for each computer, and the files will use the computers’ names as their file names.

9. Open the E:\Allfiles\Mod03\Democode\Lesson03\Demo04\Step-07.ps1 file.

The script includes ConvertTo-Html to create the final HTML report for each computer.
10. Run this script by pressing F5. When you are prompted, provide the computer name LON-SVR1.
Press Enter on a blank computer name prompt to continue. Specify C:\Reports for the output path.

11. Run this script again by pressing F5. When you are prompted, provide the computer name LON-DC1.
Press Enter on a blank computer name prompt to continue. Specify C:\Reports for the output path.
12. When the script finishes, use Internet Explorer to open the files in C:\Reports to display the results.

If you receive a Service Control Manager privilege error, ensure that you are running the ISE as
Administrator, or run the script directly from its location in the console by typing .\Step-07.ps1.
13. Close all applications once you finished this demonstration.
Writing controller scripts 3-11

Module Review and Takeaways


Best Practice
Try to always parameterize values instead of hard-coding them. Hard-coded values require more long-
term maintenance when values change. For example, if a computer will run a script locally to produce a
report about itself, use the $env:COMPUTERNAME variable to obtain the current computer name.

Review Question
Question: What types of controller scripts might you write in your organization?

Answer: Answers will vary and might include examples such as provisioning scripts, reporting
scripts, and menu scripts.
3-12 Advanced Automated Administration with Windows PowerShell

Lab Review Questions and Answers


Lab A: Writing controller scripts that display a user interface
Question and Answers
Question: How can text menus make tools easier for less-experienced users to use?

Answer: In the lab, you saw one example in which the –State parameter of Set-
AdatumComputerState was coded into the script. The user was only prompted for one or more
computer names. Menus can provide this kind of shortcut to users, helping users run tools that
otherwise might be confusing or difficult to manage.

Lab B: Writing controller scripts that produce HTML reports


Question and Answers
Question: Why might you save an HTML report file to an intranet web server?
Answer: Saving a report to a web server makes the report available by means of a web browser.
You can schedule controller scripts to produce reports regularly, and direct users and technicians
to the appropriate intranet website to view those reports.
Handling script errors 4-1

Module 4
Handling script errors
Contents:
Lesson 1: Understanding error handling 2

Lesson 2: Handling errors in a script 5


Module Review and Takeaways 8

Lab Review Questions and Answers 9


4-2 Advanced Automated Administration with Windows PowerShell

Lesson 1
Understanding error handling
Contents:
Question and Answers 3
Demonstration: Understanding the default error handling of
Windows PowerShell 3
Demonstration: Detecting errors 3
Demonstration: Capturing errors 3
Handling script errors 4-3

Question and Answers


Question: What kinds of errors can you anticipate in a script, and what actions might you take to handle
those errors?

Answer: Answers will vary. An example is being unable to connect to a computer and logging
the name off the failed computer to a file. Another example is being unable to access a file and
either displaying a custom error message or writing an event to an event log.

Demonstration: Understanding the default error handling of Windows


PowerShell
Demonstration Steps
1. Open the E:\Allfiles\Mod04\Democode\Lesson01\Demo01\Step-01.ps1 file.

2. Run each section of the script independently, as listed in the demonstration script, by selecting each
section and then pressing F8.
3. Click Yes if prompted whether to continue.

Demonstration: Detecting errors


Demonstration Steps
1. Open the E:\Allfiles\Mod04\Democode\Lesson01\Demo02\Step-01.ps1 file.

2. Run the whole script by pressing F5


The first section tries to trap a non-terminating error. This does not work, and the Catch part of the
construct never runs.

The second section tries to trap a terminating error. Notice the -ErrorAction parameter, which is used
to make the error terminating. This works. However, because the command stopped, neither
computer is queried.

The third section shows the correct approach. It uses a ForEach construct so that the Get-
CimInstance command tries only one computer at a time. This way, if an error occurs, the ForEach
construct is still able to process any remaining computer names.

You can also move the location of the NOTONLINE computer in the script to demonstrate how the
ordering affects pass 1 and pass 2.

Demonstration: Capturing errors


Demonstration Steps
1. Open the E:\Allfiles\Mod04\Democode\Lesson01\Demo03\Step-01.ps1 file.

The script relies on the fact that the most recent error is always in $error[0]. Note that the
demonstration script pipes the error object to Get-Member. The ErrorRecord object is sometimes
nested as a property of the top-level object. ErrorRecord is what provides the most usable
information about the error.

2. Open the E:\Allfiles\Mod04\Democode\Lesson01\Demo03\Step-02.ps1 file.


The script relies on the fact that all commands support the -ErrorVariable (or -EV) parameter. Note
that the variable name does not include the dollar sign ($). You use the dollar sign only to access the
content of the variable after it is populated.
4-4 Advanced Automated Administration with Windows PowerShell

3. Open the E:\Allfiles\Mod04\Democode\Lesson01\Demo03\Step-03.ps1 file.

Note that this example immediately copies $_ into another variable. Windows PowerShell uses $_ in
several situations, so you must capture its contents into your own variable.
Handling script errors 4-5

Lesson 2
Handling errors in a script
Contents:
Demonstration: Trapping errors and logging them to a text file 6
4-6 Advanced Automated Administration with Windows PowerShell

Demonstration: Trapping errors and logging them to a text file


Demonstration Steps
1. Open the E:\Allfiles\Mod04\Democode\Lesson02\Demo01\Step-01.ps1 file.

2. Note that this script has remained basically unchanged since Module 1, “Creating advanced
functions.” Quickly review the functions that are included in the script.
3. Open the E:\Allfiles\Mod04\Democode\Lesson02\Demo01\Step-02.ps1 file.

4. Note that the Get-CorpCompSysInfo function was modified to include a Try construct. In the
Windows PowerShell Integrated Scripting Environment (ISE), this should show as an error (denoted by
a red underline), because the corresponding Catch construct has not yet been added.

5. Note that the Try construct surrounds all the commands you want to skip if an error happens. That is,
if an error happens, you want no output from the function. Therefore, you skip almost everything
else.

6. Open the E:\Allfiles\Mod04\Democode\Lesson02\Demo01\Step-03.ps1 file. This adds the


corresponding but empty Catch construct.

7. Open the E:\Allfiles\Mod04\Democode\Lesson02\Demo01\Step-04.ps1 file.


8. Note that the Catch construct logs the name of the failed computer to a text file.

The construct does not log the actual error, because in some cases, you do not want to. In other
cases, you might want to.
By logging one computer name at a time to the file, you can use that file as input to your function to
retry the failed computers. Alternatively, you can pipe the file’s contents to a different function that
tries to diagnose the problem.

9. Open the E:\Allfiles\Mod04\Democode\Lesson02\Demo01\Step-05.ps1 file.

Note that the -ErrorAction parameter is set to Stop so that errors will become terminating exceptions
and be trappable. Alternatively, you can use the parameter alias -EA.
Note that the parameter is available only for commands in the Windows PowerShell. If you need to
trap exceptions for methods or other code, you have to set $ErrorActionPreference before and after
running that code.
10. Save this file as \Documents\WindowsPowerShell\Modules\DemoTools\DemoTools.psm1.
Create the folder structure if necessary.
11. From the Windows PowerShell ISE console pane, run:

Import-Module –Name DemoTools -Force

12. Open the E:\Allfiles\Mod04\Democode\Lesson02\Demo01\Step-06.ps1 file. This script


demonstrates that the name of the failed computer, LON-XX7, will be logged to the C:\Errors.txt
file.

13. Run the script by pressing F5.

14. Verify that the name LON-XX7 was logged to the C:\Errors.txt file

15. Open the E:\Allfiles\Mod04\Democode\Lesson02\Demo01\Step-07.ps1 file. The purpose of this


example is to demonstrate the use of module-level preference variables. Do not save the file.
Handling script errors 4-7

16. Note that at the beginning of the script, a $CorpErrorLogPreference variable has been added and
that it is set it to a file name. When the module is loaded into the Windows PowerShell, this variable
will be visible to the Windows PowerShell user. The user can modify the content of this variable. The
variable will be removed if the module is removed from memory.

17. Note that the Get-CorpCompSysInfo function has a new $ErrorFilePath parameter, and it is set it to
$CorpErrorLogPreference as a default value. Also added is a BEGIN block that tries to remove any
existing log file. In the Catch construct, $ErrorFilePath is used to save the names of failed computers.
This approach allows users to set a global preference for the default error log file that is used by all
the commands in the script. That can be overridden on a per-command basis by using the -
ErrorFilePath parameter.
4-8 Advanced Automated Administration with Windows PowerShell

Module Review and Takeaways


Review Question
Question: What kinds of actions might you take in response to an error?

Answer: Answers will vary and might include logging the error to a file, sending an email
message, and writing events to the event log.

Common Issues and Troubleshooting Tips


Common Issue Troubleshooting Tip

The Catch block does not run. Make sure that the commands that generate an error
are run by using -ErrorAction Stop. Notice that some
commands might not produce terminating errors
under any circumstances. That is caused by the way
the command was created, so it might be outside of
your control.
Handling script errors 4-9

Lab Review Questions and Answers


Lab: Handling errors that occur when running a script
Question and Answers
Question: What would occur if you did not include -ErrorAction Stop on the commands in a Try
construct?

Answer: It depends. For most commands, the errors would be non-terminating, so the Catch
block would not run.
Using XML, JSON, and custom-formatted data 5-1

Module 5
Using XML, JSON, and custom-formatted data
Contents:
Lesson 1: Reading, manipulating, and writing data in XML 2

Lesson 2: Working with JSON-formatted data 5


Lesson 3: Reading and manipulating custom-formatted data 7

Module Review and Takeaways 9

Lab Review Questions and Answers 10


5-2 Advanced Automated Administration with Windows PowerShell

Lesson 1
Reading, manipulating, and writing data in XML
Contents:
Demonstration: Reading XML data into memory 3
Demonstration: Searching for XML elements 3
Demonstration: Manipulating XML nodes and attributes 3
Using XML, JSON, and custom-formatted data 5-3

Demonstration: Reading XML data into memory


Demonstration Steps
1. Open the file E:\Allfiles\Mod05\Democode\Lesson01\Demo01\Step-01.ps1. The example uses a
here-string to produce a sample XML file in C:\Inventory.xml.

Note: Your lab computer might already have a file with that name. It is acceptable to
overwrite any existing file.

2. To run this script and create the sample file C:\Inventory.xml, press F5.

3. Open the file E:\Allfiles\Mod05\Democode\Lesson01\Demo01\Step-02.ps1.

4. Point out that Windows PowerShell reads the file through Get-Content, and casts it into XML
through the [xml] type accelerator.

5. Run the remaining commands one at a time. This shows how to access data in the XML file. It might
be useful to have the XML file open in Notepad so that students can see the XML code as you run
these commands.

Demonstration: Searching for XML elements


Demonstration Steps
1. Open the file E:\Allfiles\Mod05\Democode\Lesson01\Demo02\Step-01.ps1.
2. Run each command individually by selecting it and then pressing F8.

Note: You use XML Path Language (XPath) to select a single node in the first example and
multiple nodes in the second example. You can then use a ForEach construct to enumerate the
$nodes variable.
Note: You can use the InnerXML property to display the raw XML text of a node. In this
example, this property shows the selected XML.

Demonstration: Manipulating XML nodes and attributes


Demonstration Steps
1. Open the file E:\Allfiles\Mod05\Democode\Lesson01\Demo03\Step-01.ps1. The function in the
file accepts an XML document, or a string that contains XML. Strings are converted into XML
documents.

Note: The command at the end of the script runs the function. It passes strings to the
parameter.

2. Open the file E:\Allfiles\Mod05\Democode\Lesson01\Demo03\Step-02.ps1. This script adds a


ForEach construct to enumerate the <computer> nodes under the <computers> node.

3. Open the file E:\Allfiles\Mod05\Democode\Lesson01\Demo03\Step-03.ps1.

Note: The <computer> node is stored in $computer and that its Name attribute is
available as a Name property.
5-4 Advanced Automated Administration with Windows PowerShell

4. Open the file E:\Allfiles\Mod05\Democode\Lesson01\Demo03\Step-04.ps1. The file prepares for


populating the XML file with the current IP addresses. It starts by removing any existing <addresses>
node, to provide a clean start.

Note: Note the use of the ChildNodes to determine whether the computer has an
<addresses> node. If it does, the script selects that node. By using SelectSingleNode() on the
$computer variable, the search starts at the current computer node. The XPath query does not
start with //, so it does not start at the root of the XML document. The script obtains a reference
to the node by using SelectSingleNode(), and then ask the <computer> node to remove the
referenced node

5. Open the file E:\Allfiles\Mod05\Democode\Lesson01\Demo03\Step-05.ps1. The script creates an


<addresses> node by leveraging the XML document.

6. Open the file E:\Allfiles\Mod05\Democode\Lesson01\Demo03\Step-06.ps1. The file enumerates


the network adapter information objects and create a new <ipaddress> node for each one. You set
the inner text of each new node to be the IP address. You append the new nodes to the new
<addresses> node.

Note: After the ForEach construct, the script appends the <addresses> node to the
<computer> node in the XML. That attaches all the new data to the XML document.

7. Open the file E:\Allfiles\Mod05\Democode\Lesson01\Demo03\Step-07.ps1. Previously, the script


set the content of the <ipaddress> nodes. Now the script uses the Family, InterfaceIndex, and
AdapterName attributes. The script creates these attributes first, and then appends them to the
<ipaddress> node and sets their value.

Note: The script uses Out-Null to suppress the output of the SetAttributeNode() method.
You can use the same technique elsewhere to suppress output you do not want displayed.

8. Open the file E:\Allfiles\Mod05\Democode\Lesson01\Demo03\Step-08.ps1. Now that the XML


document is updated in memory, the script saves the final XML document. This is done by writing the
XML document’s OuterXML property to the pipeline.

This approach provides flexibility. You do not have to hard-code a file name into the function.
Instead, you can pipe the output of the function to Out-File or to any other appropriate command.

9. To run the script, press F5.

10. In Internet Explorer, open C:\new-inventory.xml and review the results.


11. Open the file E:\Allfiles\Mod05\Democode\Lesson01\Demo03\Step-09.ps1 and review its
content. The file illustrates an alternative approach to outputting a string to the pipeline. You add a
parameter for the output path and save the XML document there.

12. To run the script, press F5.

13. In Internet Explorer, open C:\new-inventory.xml and review the results.


Using XML, JSON, and custom-formatted data 5-5

Lesson 2
Working with JSON-formatted data
Contents:
Resources 6
Demonstration: Managing JSON data by using Windows PowerShell 6
5-6 Advanced Automated Administration with Windows PowerShell

Resources

Why use JSON?

Additional Reading: For a more comprehensive listing of differences between XML and
JSON, refer to “An Introduction to JavaScript Object Notation (JSON) in JavaScript and .NET” at
https://aka.ms/k5p8mu.

Introduction to JSON syntax

Additional Reading: For detailed JSON specifications, refer to the RFC (Request for
Comments) publication 4627 at https://aka.ms/nx0wsp.

Demonstration: Managing JSON data by using Windows PowerShell


Demonstration Steps
1. Open the file E:\Allfiles\Mod05\Democode\Lesson02\Demo01\Step-01.ps1 and run it from
Windows PowerShell ISE.

Note: The example displays the list of websites on LON-SVR1 by using the Microsoft
Internet Information Services (IIS) Administration application programming interface (API) that
you learned in Module 2, “Using Microsoft .NET Framework and REST API in Windows
PowerShell.”

2. Open the file E:\Allfiles\Mod05\Democode\Lesson02\Demo01\Step-02.ps1 and run it from


Windows PowerShell ISE.

Note: The script uses the ConvertFrom-Json cmdlet to convert the JSON representation of
the websites configuration on LON-SVR1. It then extracts the value of the id property of the first
item in the websites array.
Using XML, JSON, and custom-formatted data 5-7

Lesson 3
Reading and manipulating custom-formatted data
Contents:
Demonstration: Basic delimited parsing with ConvertFrom-String 8
Demonstration: Example-driven Parsing with ConvertFrom-String 8
5-8 Advanced Automated Administration with Windows PowerShell

Demonstration: Basic delimited parsing with ConvertFrom-String


Demonstration Steps
1. Open the file E:\Allfiles\Mod05\Democode\Lesson03\Demo01\Step-01.ps1 and run it from the
Windows PowerShell ISE.

The example first establishes a Server Message Block (SMB) connection to LON-DC1 and then
captures the output of netstat –p –tcp into the $netstatOutput Windows PowerShell variable.
2. Open the file E:\Allfiles\Mod05\Democode\Lesson03\Demo01\Step-02.ps1. From the Windows
PowerShell ISE, highlight the following lines and run the selection:

$netstatConverted = ($netstatOutput[4..$netstatOutput.Count]).Trim() | ConvertFrom-


String -Delimiter '[ ]{2,}' -PropertyNames Proto,LocalAddress,ForeignAddress,State
$netstatConverted

3. Highlight the following line and run the selection:

$netstatConverted | Where-Object -Property 'ForeignAddress' -Like 'LON-DC1:*'

Point out that the script uses the content of the $netstatOutput Windows PowerShell variable as the
input of ConvertFrom-String and parses the data by using a custom delimiter in the form of a
regular expression. It then uses the output to display the connections from LON-DC1.

Demonstration: Example-driven Parsing with ConvertFrom-String


Demonstration Steps
1. Open the file E:\Allfiles\Mod05\Democode\Lesson03\Demo02\Step-01.ps1 and run it from the
Windows PowerShell ISE.

The example first establishes an SMB connection to LON-DC1 and then captures the output of
netstat –p –tcp into the $netstatOutput Windows PowerShell variable.

2. Open the file E:\Allfiles\Mod05\Democode\Lesson03\Demo02\Step-02.ps1. From the Windows


PowerShell ISE, highlight the template definition (starting at line 6 with $template = @”) along with
the lines listed below (down to line 17) and press F8 to run the selection:

$netstatConverted = $netstatOutput | ConvertFrom-String -TemplateContent $template


$netstatConverted

3. Highlight the following line and run the selection:

$netstatConverted | Where-Object -Property 'ForeignAddress' -Like 'LON-DC1:*'

Point out that the script uses the content of the $netstatOutput Windows PowerShell variable as the
input of ConvertFrom-String. This time, the shell parses data by relying on the content of the
template. It then uses the resulting output to display the connections from LON-DC1.
Using XML, JSON, and custom-formatted data 5-9

Module Review and Takeaways


Best Practice
XML is case-sensitive. For ease of use, consider using only lowercase letters for element and attribute
names.

Review Question
Question: What are the advantages of storing data in XML instead of in a small Microsoft SQL Server
database?

Answer: XML does not require you to install any software. Also, you can easily copy it and attach
it to email messages. However, XML files are not suitable when multiple users or computers must
access the file at the same time.

Tools
The Windows PowerShell ISE can edit XML documents and can provide correct syntax highlighting for
them. You must save the file with an .xml or .ps1xml file name extension, so that the ISE interprets the file
correctly. Otherwise, the Windows PowerShell ISE tries to treat the file like a Windows PowerShell script.
5-10 Advanced Automated Administration with Windows PowerShell

Lab Review Questions and Answers


Lab: Reading, manipulating, and writing XML-formatted data
Question and Answers
Question: What kinds of data might you store in an XML file?

Answer: Answers will vary and might include server inventory and user information.
Enhancing server management with Desired State Configuration and Just Enough Administration 6-1

Module 6
Enhancing server management with Desired State
Configuration and Just Enough Administration
Contents:
Lesson 1: Understanding DSC 2
Lesson 2: Creating and deploying a DSC configuration 4

Lesson 3: Implementing JEA 8

Module Review and Takeaways 12


Lab Review Questions and Answers 13
6-2 Advanced Automated Administration with Windows PowerShell

Lesson 1
Understanding DSC
Contents:
Question and Answers 3
Resources 3
Enhancing server management with Desired State Configuration and Just Enough Administration 6-3

Question and Answers


Question: What are the advantages of using the pull model instead of the push model?

Answer: The pull model offers several advantages:


• You can configure more than one computer to have the same GUID. Doing this will cause all
those computers to pull the same configuration MOF file, resulting in all those computers
sharing the same configuration.

• Computers will check for updates to their configurations automatically, making it easier to
deploy configuration changes.

• Computers can obtain DSC resource modules from the pull server.

Resources

Overview of DSC

Additional Reading: For more information on DSC resources, refer to GitHub’s


“PowerShell DscResources page” at https://aka.ms/u4gehw.

Creating DSC configuration files

Additional Reading: You will not learn about composite resources in this course. However,
for more information, refer to “Composite resources: Using a DSC configuration as a resource” at
https://aka.ms/dls15i.

Understanding DSC resources

Additional Reading: Resource creation will not be covered in this course, but you can
learn more about it by referring to “Build Custom Windows PowerShell Desired State
Configuration Resources” at https://aka.ms/u2v2av.

Using the DSC pull model

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


PowerShell Desired State Configuration Overview” at https://aka.ms/uxjosn.

Using DSC on Linux

Additional Reading: For more information on DSC for Linux, refer to “Get started with
Desired State Configuration (DSC) for Linux” at https://aka.ms/xu3wu3.
6-4 Advanced Automated Administration with Windows PowerShell

Lesson 2
Creating and deploying a DSC configuration
Contents:
Resources 5
Demonstration: Configuring the LCM 5
Demonstration: Writing a DSC configuration file 5
Demonstration: Running the configuration file 5
Demonstration: Deploying the configuration 6
Demonstration: Verifying the configuration 6
Demonstration: Implementing a partial DSC configuration 6
Enhancing server management with Desired State Configuration and Just Enough Administration 6-5

Resources

Implementing partial DSC configuration

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


Desired State Configuration partial configurations” at https://aka.ms/r3gk46.

Demonstration: Configuring the LCM


Demonstration Steps
1. Open the file E:\Allfiles\Mod06\Democode\Lesson02\Demo01\Step-01.ps1 and run the script.
2. Examine the outcome. Note that the value of the ConfigurationMode property of the LCM is
ApplyandMonitor.
3. Open the file E:\Allfiles\Mod06\Democode\Lesson02\Demo01\Step-02.ps1 and examine the
configuration script. Note the value of the ConfigurationMode property.

4. Open the file E:\Allfiles\Mod06\Democode\Lesson02\Demo01\Step-03.ps1 and run the script.


5. Examine the outcome. Start File Explorer and open the folder
E:\Allfiles\Mod06\Democode\Lesson02\Demo01 and check whether it contains a subfolder
named AdatumLCMConfig, which contains the .mof file representing the new LCM configuration.
6. Open the file E:\Allfiles\Mod06\Democode\Lesson02\Demo01\Step-04.ps1 and run the script.

7. Examine the outcome. Note whether the value of the ConfigurationMode property of the LCM is set
to ApplyandAutoCorrect.

Demonstration: Writing a DSC configuration file


Demonstration Steps
1. Open the file E:\Allfiles\Mod06\Democode\Lesson02\Demo02\Step-01.ps1.
The configuration in this example parameterizes the node name. It specifies that three features
should be present; a fourth feature should be removed (not present or absent); and a specific folder
should exist.

Also, while not called out in this example, you may also have to specify a source for installation files
for features such as Microsoft .NET Framework.
Do not run the script at this point.

2. Open the file E:\Allfiles\Mod06\Democode\Lesson02\Demo02\Step-02.ps1.

The purpose of the second script is to demonstrate the current installation status of the specified
features.

3. Press F5 to run the script.

The features should not be installed already.

Demonstration: Running the configuration file


Demonstration Steps
1. Open the file E:\Allfiles\Mod06\Democode\Lesson02\Demo03\Step-01.ps1.

Notice that configurations all have several standard parameters that are handled automatically by
Windows PowerShell. In this example, the standard –OutputPath parameter is used to specify the path
6-6 Advanced Automated Administration with Windows PowerShell

where the MOF files should be created. When not specified, a folder is created in the current
directory.

2. To run the script, on the LON-CL1 virtual machine, press F5.

3. Use File Explorer to examine the C:\FileAndPrint folder.


4. Verify that the folder contains one MOF file named LON-SVR1.mof.

Demonstration: Deploying the configuration


Demonstration Steps
1. Open the file E:\Allfiles\Mod06\Democode\Lesson02\Demo04\Step-01.ps1.

This script uses the –Wait parameter so that your students will be able to display details about the
process.

2. To run this script, press F5. Then consider taking a short break (5–10 minutes) to give the LCM
enough time to process the new configuration.

Demonstration: Verifying the configuration


Demonstration Steps
1. Open the file E:\Allfiles\Mod06\Democode\Lesson02\Demo05\Step-01.ps1.

2. To run this script, press F5. Keep in mind that you should allow 5–10 minutes after the previous
demonstration. That time is needed for the LCM to process the configuration and install the specified
features.

Demonstration: Implementing a partial DSC configuration


Demonstration Steps
1. Open the file E:\Allfiles\Mod06\Democode\Lesson02\Demo06\Step-01.ps1.
2. Run the script by pressing F5

3. Examine the outcome. Note that the value of the PartialConfigurations property of the LCM is
currently not set.
4. Open the file E:\Allfiles\Mod06\Democode\Lesson02\Demo06\Step-02.ps1 and run the script.
5. Examine the outcome. Start File Explorer, open the folder
E:\Allfiles\Mod06\Democode\Lesson02\Demo06, and then note that it contains a subfolder
named AdatumPartialConfig, which contains the .mof file representing the new LCM configuration.
Also, note that the current value of the PartialConfigurations property of the LCM is currently set to
{[PartialConfiguration]AdatumEnvVars, [PartialConfiguration]AdatumRegistry]}.

6. Open the file E:\Allfiles\Mod06\Democode\Lesson02\Demo06\Step-03.ps1 and run the script.

7. Examine the outcome. Start File Explorer and open the folder
E:\Allfiles\Mod06\Democode\Lesson02\Demo06; note that it contains a subfolder named
AdatumEnvVars, which contains the .mof file representing the new partial DSC configuration.

8. Open the file E:\Allfiles\Mod06\Democode\Lesson02\Demo06\Step-04.ps1 and run the script.


Enhancing server management with Desired State Configuration and Just Enough Administration 6-7

9. Examine the outcome. Start File Explorer and open the folder
E:\Allfiles\Mod06\Democode\Lesson02\Demo06; note that it contains a subfolder named
AdatumRegistry, which contains the .mof file representing the new partial DSC configuration.

10. Open the file E:\Allfiles\Mod06\Democode\Lesson02\Demo06\Step-05.ps1 and run the script.


11. Examine the outcome. Note that it contains a listing of the contents of the
HKLM\SOFTWARE\AdatumRegKey1 key, including the entry AdatumRegVal1 with the value of 1.
It also includes the value of the system environment variable named AdatumEnvVar1, which is set to
1.
6-8 Advanced Automated Administration with Windows PowerShell

Lesson 3
Implementing JEA
Contents:
Resources 9
Demonstration: Configuring and using JEA 9
Enhancing server management with Desired State Configuration and Just Enough Administration 6-9

Resources

Identifying JEA prerequisites

Additional Reading: For more information on WMF 5.1, refer to “Windows Management
Framework 5.1” at https://aka.ms/ccfrjb.

Defining JEA role capabilities

Additional Reading: For more information on JEA role capabilities, refer to “JEA Role
Capabilities” at https://aka.ms/fcm9zc.

Creating JEA session configurations

Additional Reading: For more information on session configurations, refer to “JEA Session
Configurations” at https://aka.ms/np73t7.

Using DSC to deploy JEA

Additional Reading: For more information about deploying JEA via DSC, refer to
“Registering JEA Configurations” at https://aka.ms/cz6kwh.

Demonstration: Configuring and using JEA


Demonstration Steps
1. From Windows PowerShell ISE on LON-CL1, open the
E:\Allfiles\Mod06\Democode\Lesson03\Demo01\Step-01.ps1 file.
Point out that the script checks for the presence of the role capabilities file named
AdatumWebAdminJEARole.psrc in the E:\Allfiles\Mod06\Democode\Lesson03\Demo01 folder
on LON-CL1 and, if it does not exist, it creates one. It also creates an empty module file named
AdatumJEA.psm1 on LON-SVR1 in the C:\Program
Files\WindowsPowerShell\Modules\AdatumJEA folder and the corresponding module manifest
named AdatumJEA.psd1 on LON-SVR1 in the same location. It then creates a subfolder named
RoleCapabilites under the AdatumJEA folder on LON-SVR1 and copies the role capabilities file to
that location.

2. Run the script by pressing F5, and then verify the changes.
3. In the same Windows PowerShell ISE session, open the
E:\Allfiles\Mod06\Democode\Lesson03\Demo01\AdatumWebAdminJEARole.psrc file. This is a
pre-configured role capabilities file used in this task. Examine its content and point out the following
entries:

VisibleCmdlets = 'Test-Connection', 'Get-Website', @{ Name = 'Stop-Website';


Parameters = @{ Name = 'Name'; ValidateSet = 'Default Web Site'}}, @{ Name = 'Start-
Website'; Parameters = @{ Name = 'Name'; ValidateSet = 'Default Web Site'}}
VisibleExternalCommands = 'C:\Windows\System32\netstat.exe'
VisibleProviders = 'Variable'
6-10 Advanced Automated Administration with Windows PowerShell

Explain that these entries will allow you to use JEA to delegate the tasks of stopping and starting IIS
websites, and testing connectivity by running the Test-Connection cmdlet and the netstat utility on
LON-SVR1.

4. In the same Windows PowerShell ISE session, open the


E:\Allfiles\Mod06\Democode\Lesson03\Demo01\Step-02.ps1 file and run the script. Point out
that this script checks for the presence of the session configuration file named
AdatumWebAdminEndpoint.pssc in the E:\Allfiles\Mod06\Democode\Lesson03\Demo01 folder
and, if it does not exist, it creates one. It also creates an Active Directory group named IISAdmins and
adds a user named Abbi to the group. Next, the script copies the session configuration file to the
C:\Program Files\WindowsPowerShell\Modules\AdatumJEA folder on LON-SVR1.
5. In the same Windows PowerShell ISE session, open the
E:\Allfiles\Mod06\Democode\Lesson03\Demo01\AdatumWebAdminEndpoint.pssc file. This is a
pre-configured session configuration file used in this task. Examine its content and point out the
following entries:

SessionType = ‘RestrictedRemoteServer’
TranscriptDirectory = 'C:\Transcripts'
RunAsVirtualAccount = $true
RoleDefinitions = @{ 'ADATUM\IISAdmins' = @{ RoleCapabilities =
'AdatumWebAdminJEARole' }}

Explain that these entries will ensure that the session applies JEA constraints, allows you to record
tasks carried out during JEA sessions, implements local virtual accounts to provide security context for
running these tasks, and limits access to the roles defined in the role capabilities file to members of
the ADATUM\IISAdmins role.
6. In the same Windows PowerShell ISE session, open the
E:\Allfiles\Mod06\Democode\Lesson03\Demo01\Step-03.ps1 file and run the script. Point out
that this script registers the JEA configuration on LON-SVR1 using
adatum.windows.demoiismanagement as the JEA endpoint configuration name.

Note: Ignore any error messages that state “Processing data from remote server LON-SVR1
failed with the following error message: The I/O operation has been aborted because of either a
thread exit or an application request.”

7. In the same Windows PowerShell ISE session, open the


E:\Allfiles\Mod06\Democode\Lesson03\Demo01\Step-04.ps1 file and run the script. Point out
that this script configures the ADATUM\Abbi credentials for the remote JEA session to LON-SVR1
and initiates a remote Windows PowerShell session to the JEA endpoint you configured in the
previous tasks.

8. From the [LON-SVR1]: PS> prompt, run the following commands and examine their outcome:

Get-Command

Point out that this command lists functions and cmdlets that are available within the JEA session.

Get-Website

Point out that this command lists the status of websites on LON-SVR1, allowing delegated admins to
determine that Default Web Site is running.

Stop-Website –Name ‘Default Web Site’


Enhancing server management with Desired State Configuration and Just Enough Administration 6-11

Point out that this command stops the Default Web Site.

Get-WebSite

Point out that this command lists the status of websites on LON-SVR1, allowing delegated admins to
determine that Default Web Site is stopped.

Start-Website –Name ‘Default Web Site’

Point out that this command starts the Default Web Site.

Test-Connection –ComputerName LON-CL1

Point out that this cmdlet allows you to test connectivity to LON-CL1.

netstat -ano

Point out that this executable allows you to list existing inbound connections to LON-SVR1.

ping LON-CL1

Point out that this command fails because it is not part of the role capabilities that you defined.
9. After you complete the demonstration, type the following to terminate the remoting session:

exit
6-12 Advanced Automated Administration with Windows PowerShell

Module Review and Takeaways


Best Practice
As a new technology, DSC is evolving quickly as customers begin to use it in their production
environments. If you plan to use DSC, you should connect to the community of DSC users so that you can
share your experiences and take advantage of the knowledge of others.

Review Question
Question: Why might you have to create your own DSC resources?

Answer: If an existing resource does not meet your needs, you might have to write your own
DSC resource. Most DSC resources are Windows PowerShell script modules. Therefore, you can
sometimes use an existing resource as the starting point for making additions or modifications.
Make sure that you give your modified resource a new, unique name.

Tools
The PowerShell Gallery at https://aka.ms/ihld75 includes additional DSC resource modules from Microsoft.
It also includes tools that help you design and create new DSC resources and troubleshoot DSC problems.

Common Issues and Troubleshooting Tips


Common Issue Troubleshooting Tip

LCM is not enforcing configurations. Check the LCM configuration. The LCM can be
configured to apply the configuration one time,
either to only monitor the configuration or to
monitor and reapply the configuration.

Errors occur when authoring or running a On computers running Windows Server 2012 R2 or
configuration. Windows 8.1, make sure that update KB2883200 is
installed. Also make sure that WMF 5.0 or newer is
installed.

DSC is not working. Make sure that WMF 5.0 or newer is installed. Use
the DSC Diagnostics module in the DSC Resource
Kit to enable detailed logging and to review the
log.
Enhancing server management with Desired State Configuration and Just Enough Administration 6-13

Lab Review Questions and Answers


Lab A: Creating and deploying a DSC configuration
Question and Answers
Question: What are some differences between using DSC and using a GPO to configure computers?

Answer: Currently, DSC is intended primarily for server configuration scenarios, and the available
DSC resources reflect that intent. Unlike a GPO, DSC does not have a dependency on Active
Directory Domain Services (AD DS) and can be used to configure computers that are not
members of a domain. However, a GPO has more fine-grained targeting and filtering criteria and
includes the ability to target multiple configurations to a given computer. At the time of writing
this course, the two technologies are complementary and serve different purposes in an
organization.

Lab B: Creating and using JEA

Question and Answers


Question: What approach would you consider when implementing JEA in your environment?
Answer: The answers might vary, but the Windows PowerShell-based implementation covered in
the lab is suitable for configuring individual servers. For a larger number of servers, using the
DSC-based deployment methodology might be beneficial. DCS is more complex; however, it
offers an extra benefit of preventing accidental or intentional configuration drift.
Analyzing and debugging scripts 7-1

Module 7
Analyzing and debugging scripts
Contents:
Lesson 1: Debugging in Windows PowerShell 2

Lesson 2: Analyzing and debugging an existing script 5


Module Review and Takeaways 8

Lab Review Questions and Answers 9


7-2 Advanced Automated Administration with Windows PowerShell

Lesson 1
Debugging in Windows PowerShell
Contents:
Question and Answers 3
Demonstration: Displaying debug output 3
Demonstration: Setting breakpoints 4
Demonstration: Debugging in the ISE 4
Analyzing and debugging scripts 7-3

Question and Answers


Question: What assumptions can you make about the example script?

Answer: The command at the end of the script assumes that the ProcArchitecture property that
the function produces contains the same data as the OSArchitecture property. Those properties
come from the Win32_Processor and Win32_OperatingSystem classes, respectively.
Question: Why might you specify an action for a breakpoint instead of enabling the breakpoint to
suspend execution?

Answer: Actions can be useful when you must debug a script that runs unattended, such as a
script that Windows Task Scheduler is running. You can use actions to log information that you
can later use to diagnose and resolve errors.

Demonstration: Displaying debug output


Demonstration Steps
1. Open the file E:\Allfiles\Mod07\Democode\Lesson01\Demo01\Step-01.ps1.
2. Press F5 to run the script and verify that it produces no output.

Note: The function uses the [CmdletBinding()] attribute. That attribute enables the –
Debug switch.

3. Open the file E:\Allfiles\Mod07\Democode\Lesson01\Demo01\Step-02.ps1.

Note: A debug command is added after the Common Information Model (CIM) queries are
completed. Because those query results are stored in variables, the debug output enables you to
examine the query output and verify property contents.

4. Press F5 to run the script and verify that it produces no output.


5. Open the file E:\Allfiles\Mod07\Democode\Lesson01\Demo01\Step-03.ps1.

Note: Notice that –Debug was added to the command at the end of the script.

6. Press F5 to run the script.


7. When prompted, select the option to suspend the script.

Note: The shell prompt has an additional angle bracket (>), indicating that you are in a
nested prompt.

8. Run the following two commands:

$proc | Select *
$os | Select *

Note: Notice the contents of the AddressWidth property of the first object and the
OSArchitecture property of the second object. One is 64 and the other is 64-bit. These values do
not match, although the command assumes that they do match.
7-4 Advanced Automated Administration with Windows PowerShell

9. To return to the debug prompt, type Exit. Select the option to halt the command.

10. Open the file E:\Allfiles\Mod07\Democode\Lesson01\Demo01\Step-04.ps1.

Note: The new script removes the –bit from the OSArchitecture property and converts the
value to an integer.

11. Press F5 to run the script and verify that it completes successfully. Click Yes if prompted.

Demonstration: Setting breakpoints


Demonstration Steps
1. Open the file E:\Allfiles\Mod07\Democode\Lesson01\Demo02\Step-01.ps1. This is the same
example bug from the previous demonstration.

2. Save the script as C:\DebugDemo.ps1 so that the demonstration will work.

3. To run the script, press F5.


4. Note that two breakpoints are set when you run the script:
o The breakpoint on line 18 suspends the script. You should examine the $proc and $os variables,
just as you did in the previous demonstration. To resume script execution, run exit.
o The other breakpoint runs when the $properties variable is changed. This does not suspend
script execution but does log the contents of the variable to the file C:\Debug.txt. Examine the
file’s contents after you run this script

5. To return to the console prompt, type exit twice.

Demonstration: Debugging in the ISE


Demonstration Steps
1. Open the file E:\Allfiles\Mod07\Democode\Lesson01\Demo03\Step-01.ps1.

2. To set a breakpoint, move the cursor to line 19, and then press F9.

3. To run the script, press F5.


4. When the breakpoint runs, examine the $os and $proc variables as you did in the previous
demonstration.

5. Return to the Script pane in the Windows PowerShell ISE. Press F11 to run one line of code at a time,
noticing the highlighted line.

6. Point to the $obj variable and notice what displays.

7. To halt script execution, in the Debug menu, click Stop Debugger.


Analyzing and debugging scripts 7-5

Lesson 2
Analyzing and debugging an existing script
Contents:
Demonstration: Debugging a script 6
7-6 Advanced Automated Administration with Windows PowerShell

Demonstration: Debugging a script


Demonstration Steps
1. Open the file E:\Allfiles\Mod07\Democode\Lesson02\Demo01\Step-01.ps1.

2. Press F5 to run the script. Note that triggers an error message pointing to the syntax problem. There
is a missing closing bracket preventing it from running.
3. Open the file E:\Allfiles\Mod07\Democode\Lesson02\Demo01\Step-02.ps1.

Note that the syntax issue has been fixed and the script was reformatted. Changing the formatting
makes the script easier to read and understand.

4. Examine the script line by line and discuss what each line should do. Document expected variable and
property contents by using note paper or a white board. The script should display services and their
process ID numbers.
5. Press F5 to run the script. Note the invalid query error.

6. Open the file E:\Allfiles\Mod07\Democode\Lesson02\Demo01\Step-03.ps1.

7. Note that Debug output has been added to verify the contents of $service.name and
$service.processid.

8. Press F5 to run the script.

Note that the queried process ID is 0. The issue results because the objects that Get-Service produces
do not have a ProcessID property. Click Halt Command and verify that by running the following:

Get-Service | Select *

9. You must identify another way to retrieve this information. One possibility is to use the
Win32_Service class. Run the following command and verify that the objects have a ProcessID
property:

Get-WmiObject Win32_Service | Select * -first 1

10. Open the file E:\Allfiles\Mod07\Democode\Lesson02\Demo01\Step-04.ps1.

11. You have verified that Win32_Service has the information that you need. Notice the modified
command that now uses Get-WmiObject instead of Get-Service.

12. Press F5 to run the script.

13. The output consists of multiple “System Idle Process” entries. That was not the intended result.
14. Open the file E:\Allfiles\Mod07\Democode\Lesson02\Demo01\Step-05.ps1.

15. Press F5 to run the script again.

16. If the process id for the queried service is not 0, click Yes. Repeat this step if necessary until the debug
output shows a process ID of zero.

17. Click Halt Command.

18. At the prompt, run the following command. Replace x with the name of the service that displayed
process id of 0 in the debug output

Get-WmiObject Win32_Service –Filter "name='x'" | Select *


Analyzing and debugging scripts 7-7

Note: Notice that the service is stopped and that ProcessID is zero. When a service is not
running, it has no associated process. This means that you should modify the script to query only
running services or to check for a process ID of zero.

19. Open the file E:\Allfiles\Mod07\Democode\Lesson02\Demo01\Step-06.ps1.

Note: The script now checks for a process ID of zero. It provides the process name “(Not
started)” when the process ID is zero, or the actual process name when the process ID is not zero.

20. Press F5 to run the script.

21. Verify that the script executes as expected.

22. Open the file E:\Allfiles\Mod07\Democode\Lesson02\Demo01\Step-07.ps1.

This is the same script with the original error restored.

23. In Windows PowerShell ISE, set a breakpoint on line 16 by positioning the cursor on that line and
pressing F9.
24. Press F5 to run the script

25. To examine the current service object’s properties, run $service | select *.
26. In the menu, click Debug and then click Stop Debugger.

27. Open the file E:\Allfiles\Mod07\Democode\Lesson02\Demo01\Step-08.ps1.

Follow the instructions in the comments at the top of the script to demonstrate running the script
one line at a time.
7-8 Advanced Automated Administration with Windows PowerShell

Module Review and Takeaways


Best Practice
If you plan to use Write-Debug, you can add those commands as you write a new script. This enables you
to turn debugging on and off immediately, if necessary.

Review Question
Question: How can you make debugging easier in a complex script?

Answer: You can make debugging easier by breaking the script into smaller parts and running
each part on its own. Running individual commands in the console can help you ensure that each
command is correct and that the command’s output matches what the script assumes.

Real-world Issues and Scenarios


Debugging on remote computers can be difficult. For example, Windows PowerShell Remoting does not
support breakpoints and debug output. Usually, you must debug the script on the computer where it is
running, or copy the script to your computer and debug it there.
Analyzing and debugging scripts 7-9

Lab Review Questions and Answers


Lab: Analyzing and debugging an existing script
Question and Answers
Question: How does using properly formatted scripts speed up the debugging process?

Answer: Correctly formatted scripts are easier to read and make it easier to set breakpoints and
add debug output.
Understanding Windows PowerShell workflow 8-1

Module 8
Understanding Windows PowerShell workflow
Contents:
Lesson 1: Understanding Windows PowerShell workflow 2

Module Review and Takeaways 4


Lab Review Questions and Answers 5
8-2 Advanced Automated Administration with Windows PowerShell

Lesson 1
Understanding Windows PowerShell workflow
Contents:
Resources 3
Demonstration: A workflow example 3
Understanding Windows PowerShell workflow 8-3

Resources

Workflow differences

Additional Reading: For a complete list of differences between workflows and Windows
PowerShell scripts, refer to: “Getting Started with Windows PowerShell workflow” at
https://aka.ms/qjemsg.

Demonstration: A workflow example


Demonstration Steps
1. Open the E:\Alfiles\Mod08\Democode\Lesson01\Demo01\Step-01.ps1 file.

2. The name of the example workflow is Get-FolderSize. You can run this example exactly as you would
run a command—just by using the workflow name.

3. Press F5 to run the script.


4. Notice that running a workflow takes somewhat longer to start, because the script must be translated
to Extensible Application Markup Language (XAML) and passed to Windows Workflow Foundation for
execution.

The workflow defines one parameter, –Path. This is a string parameter that can accept an array of
values.

Notice the use of ForEach –Parallel to process folder paths in parallel.

The $size variable exists at the workflow level and would be persisted if a checkpoint was taken.
8-4 Advanced Automated Administration with Windows PowerShell

Module Review and Takeaways


Review Question
Question: When might you want to use a workflow?

Answer: Answers will vary. In the past, frequently workflows were seen as a good option for
performing long-running, multistep tasks such as provisioning a new server. However, starting
with Windows PowerShell 4.0, Desired State Configuration became more suitable for that
particular task. The example workflow included in the demo of this module uses the parallel
execution feature of workflow to calculate folder sizes. Although the other features of workflow
are not relevant in this case, the parallel execution makes the long-running task somewhat faster.

Workflows also offer benefits for administrators who must account for the possibility of transient
errors or intermittent network connectivity. In the lab of this module, you used a workflow to
perform a controlled reboot of multiple servers and to continue workflow execution once the
servers were back online. In this case, you can also take advantage of the support for both the
parallel and sequential execution of activities within the same workflow. This enables you to
implement more complex scenarios, where you need to reboot groups of servers in a specific
sequence in the shortest possible time.

Another benefit of workflows is support for persisting their state through checkpoints. This means
that it is possible to reboot the computer where the workflow is running and resume its
execution afterwards.

Real-world Issues and Scenarios


Because workflows are translated to a different language and run by a different piece of software, they
can be more complex to write and debug than ordinary Windows PowerShell scripts. Careful testing is
usually required to make sure that a workflow runs according to your expectations.

Common Issues and Troubleshooting Tips


Common Issue Troubleshooting Tip

Workflow will not run. Make sure that you are using Windows PowerShell 3.0
or newer versions. Workflows do not exist in earlier
versions.
Understanding Windows PowerShell workflow 8-5

Lab Review Questions and Answers


Lab: Creating and running a Windows PowerShell workflow
Question and Answers
Question: What is the benefit of using workflows when performing reboots of multiple computers?

Answer: You benefit from the support for parallel execution, which you can use to perform
simultaneous reboots of multiple servers. At the same time, you can still enforce a sequential
progress of activities within a workflow. This feature enables you to implement more complex
scenarios in which some servers must be online while the workflow carries out reboots of others.
For example, in the lab, there are two separate groups. The first one contains domain controllers
and the second one consists of domain member servers. By splitting servers into these two
groups, you minimize the possibility of the authentication issues that are likely to occur if reboots
of domain controllers and domain member servers happen at the same time.
Windows PowerShell workflows also provide support for the –Wait parameter of the Restart-
Computer activity, which waits for the remote computer to come back online before proceeding
with the next activity.

Note: The Restart-Computer Windows PowerShell cmdlet includes support for


the –Wait, –For, and –Delay parameters, which offer the equivalent functionality.

Question: What are the benefits of executing a workflow as a job?

Answer: The primary advantage is the ability to run workflows unattended, while still providing
the ability to control their execution by using Windows PowerShell job-specific commands, such
as Suspend-Job and Resume-Job. This does not preclude the possibility of capturing any output
that a job generates because you can obtain it by running the Receive-Job command.
Additionally, you can use the job scheduling functionality and run workflows on the dates and at
the times you choose, without having to invoke them interactively. Lastly, executing a workflow
as a job helps when the computer running a workflow becomes temporarily unavailable, for
example, due to a reboot.

Anda mungkin juga menyukai