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.
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.
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.
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.
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.
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.
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.
Module 1
Creating advanced functions
Contents:
Lesson 1: Converting a command into an advanced function 2
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
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
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.
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
!?
Press F5 to run this script. You do not have to save it as a script module.
Creating advanced functions 1-9
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
Lesson 5
Producing complex function output
Contents:
Demonstration: Creating and producing custom objects 13
Creating advanced functions 1-13
9. Open E:\Allfiles\Mod01\Democode\Lesson05\Demo01\Step-09.ps1.
12. Then, in the same Windows PowerShell ISE window, run the following code:
Lesson 6
Documenting functions by using comment-based
Help
Contents:
Demonstration: Adding comment-based Help to a function 15
Creating advanced functions 1-15
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
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.
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
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
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.
• 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.
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.
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.
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.
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.
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
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
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.
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
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:
• REST API Overview for Visual Studio Team Services and Team Foundation Server -
https://aka.ms/a9iofb
Additional Reading: For more information, refer to the “Components of a REST API
request/response” section of https://aka.ms/vmiy1i.
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.
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
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.
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.
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?
Module 3
Writing controller scripts
Contents:
Lesson 1: Understanding controller scripts 2
Lesson 1
Understanding controller scripts
Contents:
Question and Answers 3
Writing controller scripts 3-3
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
( ) 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.
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
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.
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.
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,
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:
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
You want to create reports containing tables with custom formatted cells. What should you do?
( ) Use ConvertTo-Html with the -Head parameter
Answer:
( ) Use ConvertTo-Html with the -Head parameter
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
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.
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.
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.
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
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.
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
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
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.
Module 4
Handling script errors
Contents:
Lesson 1: Understanding error handling 2
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
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.
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.
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.
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.
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
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.
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.
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:
14. Verify that the name LON-XX7 was logged to the C:\Errors.txt file
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
Answer: Answers will vary and might include logging the error to a file, sending an email
message, and writing events to the event log.
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
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 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
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.
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.
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.
Note: The command at the end of the script runs the function. It passes strings to the
parameter.
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
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
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.
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.
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.
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
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.
Additional Reading: For detailed JSON specifications, refer to the RFC (Request for
Comments) publication 4627 at https://aka.ms/nx0wsp.
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.”
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
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:
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.
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.
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
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
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 1
Understanding DSC
Contents:
Question and Answers 3
Resources 3
Enhancing server management with Desired State Configuration and Just Enough Administration 6-3
• 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: 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.
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.
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
7. Examine the outcome. Note whether the value of the ConfigurationMode property of the LCM is set
to ApplyandAutoCorrect.
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.
The purpose of the second script is to demonstrate the current installation status of the specified
features.
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.
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.
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.
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]}.
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.
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.
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
Additional Reading: For more information on WMF 5.1, refer to “Windows Management
Framework 5.1” at https://aka.ms/ccfrjb.
Additional Reading: For more information on JEA role capabilities, refer to “JEA Role
Capabilities” at https://aka.ms/fcm9zc.
Additional Reading: For more information on session configurations, refer to “JEA Session
Configurations” at https://aka.ms/np73t7.
Additional Reading: For more information about deploying JEA via DSC, refer to
“Registering JEA Configurations” at https://aka.ms/cz6kwh.
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:
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.
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.”
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.
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.
Point out that this command starts the Default Web Site.
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
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.
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
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.
Module 7
Analyzing and debugging scripts
Contents:
Lesson 1: Debugging in Windows PowerShell 2
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
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.
Note: The function uses the [CmdletBinding()] attribute. That attribute enables the –
Debug switch.
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.
Note: Notice that –Debug was added to the command at the end of the script.
Note: The shell prompt has an additional angle bracket (>), indicating that you are in a
nested prompt.
$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.
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.
2. To set a breakpoint, move the cursor to line 19, and then press F9.
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.
Lesson 2
Analyzing and debugging an existing script
Contents:
Demonstration: Debugging a script 6
7-6 Advanced Automated Administration with Windows PowerShell
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.
7. Note that Debug output has been added to verify the contents of $service.name and
$service.processid.
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:
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.
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.
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.
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
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.
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.
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.
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
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.
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
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.
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.
The workflow defines one parameter, –Path. This is a string parameter that can accept an array of
values.
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
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.
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
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.
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.