Documente Academic
Documente Profesional
Documente Cultură
10961C
Automating Administration with Windows
PowerShell
Companion Content
ii Automating Administration with Windows PowerShell
Information in this document, including URL and other Internet Web site references, is subject to change
without notice. Unless otherwise noted, the example companies, organizations, products, domain names,
e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with
any real company, organization, product, domain name, e-mail address, logo, person, place or event is
intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the
user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in
or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical,
photocopying, recording, or otherwise), or for any purpose, without the express written permission of
Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property
rights covering subject matter in this document. Except as expressly provided in any written license
agreement from Microsoft, the furnishing of this document does not give you any license to these
patents, trademarks, copyrights, or other intellectual property.
The names of manufacturers, products, or URLs are provided for informational purposes only and
Microsoft makes no representations and warranties, either expressed, implied, or statutory, regarding
these manufacturers or the use of the products with any Microsoft technologies. The inclusion of a
manufacturer or product does not imply endorsement of Microsoft of the manufacturer or product. Links
may be provided to third party sites. Such sites are not under the control of Microsoft and Microsoft is not
responsible for the contents of any linked site or any link contained in a linked site, or any changes or
updates to such sites. Microsoft is not responsible for webcasting or any other form of transmission
received from any linked site. Microsoft is providing these links to you only as a convenience, and the
inclusion of any link does not imply endorsement of Microsoft of the site or the products contained
therein.
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
Getting started with Windows PowerShell
Contents:
Lesson 1: Overview and background of Windows PowerShell 2
Lesson 1
Overview and background of Windows PowerShell
Contents:
Question and Answers 3
Resources 3
Demonstration: Configuring the console 3
Demonstration: Configuring the ISE 4
Getting started with Windows PowerShell 1-3
Answer: The ISE supports richer editing capabilities and can display a wider range of fonts. It is
also compatible with double-byte character sets, making it compatible with a wider variety of
written languages. However, if you are just running a few commands, the console is sufficient.
Resources
Additional Reading: For more information about installing and configuring WMF 5.1, refer
to “Install and Configure WMF 5.1” at https://aka.ms/u33mya.
Additional Reading: For more information on the Windows Management Framework 5.1,
refer to “Microsoft Download Center” at https://aka.ms/i31ojp.
Additional Reading: For a list of updates to the Windows Console in Windows Server
2016, refer to “What's New in the Windows Console in Windows Server 2016 Technical Preview”
at https://aka.ms/ebr7o4.
2. When Windows PowerShell is running, right-click the icon on the taskbar, and then select Pin to
taskbar.
Note: Ensure that the window title bar reads Administrator and that it does not include
(x86).
3. Select the control box in the upper-left corner of the console application window, and then select
Properties from the pop-up menu.
4. On the Font tab, select Consolas, and then select an appropriate font size (a font size of 20– 28
points is usually appropriate for a display on a projector in front of the class).
5. On the Layout tab, change the Window Size area’s Width and Height values so that the entire
window fits on the screen.
6. After you do this, set the Screen Buffer area’s Width value to be the same as the Window Size
Width value. Make sure that the horizontal scroll bar does not display at the bottom of the window.
Select OK.
7. To start a transcript of the Windows PowerShell session, type the following command in the console,
and then press Enter:
Start-Transcript C:\Day1.txt
1-4 Automating Administration with Windows PowerShell
Get-ChildItem
9. Select the output of the previous command, and then press Enter.
10. Click Start, type notepad, and then select the Notepad icon.
11. Paste the contents of the clipboard into the Notepad window.
13. Press the Up arrow key to display the command that you entered previously.
14. Close the Windows PowerShell window.
15. Open File Explorer, and then browse to and open C:\Day1.txt.
2. On the ISE toolbar, select the Show Script Pane Right icon, select the Show Script Pane Maximized
icon, and then select Show Script Pane Top. Switch to single-pane view by selecting Show Script
Pane Maximized.
3. Use the blue arrow in the upper-right corner of the pane to show and hide the Script pane, toggling
between the script and console panes.
4. Select the Show Command Add-on and Show Command Window options to show and hide the
command add-on and the command window.
5. Use the slider in the lower-right corner of the window to adjust the font size in the console and the
Script pane.
6. On the Tools menu in the ISE, select Options. Select Manage Themes and then select a theme, such
as Presentation. Select OK to close the dialog boxes.
7. Close the Windows PowerShell ISE.
Getting started with Windows PowerShell 1-5
Lesson 2
Understanding command syntax
Contents:
Question and Answers 6
Demonstration: Viewing help 6
Demonstration: Using About files 7
1-6 Automating Administration with Windows PowerShell
Answer: You can use what you know about cmdlet name structures to help you guess the name
of the cmdlet. You know that Get retrieves resources so that you can work with their properties.
You also know that the nouns associated with Active Directory have the prefix AD. Based on this
information, you can use the Get-Help command and a wildcard value for the cmdlet name to
search for possible cmdlets by running the command Get-Help Get-AD*. Because you are
looking for the cmdlets that operate specifically on computers, you could even check if Get-Help
Get-ADComputer returns results.
Question: You wish to join multiple computers to the Adatum domain. The Add-Computer cmdlet’s -
ComputerName parameter accepts multiple values. Which of the following is a set of valid values for this
parameter?
( ) -ComputerName LON-CL2;LON-CL3;LON-CL4
( ) -ComputerName LON-CL2,LON-CL3,LON-CL4
Answer:
( ) -ComputerName LON-CL2;LON-CL3;LON-CL4
( ) -ComputerName “LON-CL2, LON-CL3, LON-CL4”
The correct way to pass multiple values to a parameter that accepts them is by separating them
with a comma and no spaces. In option 1, a semicolon is not a valid separator for parameter
values. In option 2, the entire string, including commas and spaces, will be passed as a single
value. In option 3, spaces are not a valid separator for parameter values. In option 4, you do not
pass multiple parameter values by specifying the parameter multiple times.
2. In the Windows PowerShell console, type the following text, and then press Enter:
help Get-ChildItem
3. Discuss the basic help information for the Get-ChildItem command. Point out the –Recurse switch.
4. In the Windows PowerShell console, type the following text, and then press Enter:
Get-Help Get-ChildItem
5. Point out the difference between this output and the paged output of help.
Getting started with Windows PowerShell 1-7
Note: You might need to reduce the size of the console window to demonstrate the
paging of the output. If the console window is full screen, the command might display the output
in the single screen because it fits. As a result, there will be no paging. The content is otherwise
the same.
6. To display the floating window help, in the Windows PowerShell console, type the following text, and
then press Enter:
7. To display the usage examples as part of the help output, in the Windows PowerShell console, type
the following text, and then press Enter:
8. If you have an appropriate host computer or virtual machine that has Internet access (as mentioned
in the preparation steps), you can display the online help by typing the following text in the Windows
PowerShell console, and then pressing Enter:
Get-Help about*
Get-Help about_aliases
Get-Help *beep*
1-8 Automating Administration with Windows PowerShell
Lesson 3
Finding commands
Contents:
Question and Answers 9
Resources 9
Demonstration: Viewing modules 9
Demonstration: Searching for cmdlets 10
Demonstration: Using aliases 10
Getting started with Windows PowerShell 1-9
Answer: Get-Help searches for help topics. Get-Command searches for commands. There
should be a help topic for every cmdlet, but no one enforces this. As a result, Get-Help might not
return anything for an existing command that does not have a help topic.
Additionally, when no results return when querying a command name, Get-Help will perform a
full-text search of the help files by using the same query value. Get-Command has no such
capability, and as a result, Get-Help might return results when Get-Command does not.
Resources
Finding cmdlets
2. In the Windows PowerShell console, type the following command, and then press Enter:
Get-Module
3. In the Windows PowerShell console, type the following command, and then press Enter:
Get-ADUser Lara
4. In the Windows PowerShell console, type the following command, and then press Enter:
Get-Module
5. In the Windows PowerShell console, type the following command, and then press Enter:
Get-Module -ListAvailable
6. Scroll through the results, noting that all these modules are loaded or are available to load.
7. In the Windows PowerShell console, type the following command, and then press Enter:
Import-Module ServerManager
8. In the Windows PowerShell console, type the following command, and then press Enter:
1-10 Automating Administration with Windows PowerShell
Get-Module
2. In the address bar, type enable network adapter with powershell, and then press Enter.
3. One of the top results should be the TechNet topic for Enable-NetAdapter. Open the topic and
review it with the class.
4. Go to http://www.powershellgallery.com.
5. In the Search Items box, type dns configuration, and then press Enter.
8. On LON-CL1, in the Windows PowerShell console, type the following command, and then press
Enter:
Get-Command *net*
Note: The results also include applications found in the Windows system folder that have
net in the name.
9. In the Windows PowerShell console, type the following command, and then press Enter:
10. Review the results with the class, noting the effect of the -Category parameter.
dir
Get-ChildItem
Get-Alias dir
Getting started with Windows PowerShell 1-11
list
Note: The results are the same as they are for dir and Get-ChildItem.
Note: The results include both dir and list, along with others.
1-12 Automating Administration with Windows PowerShell
Review Question
Question: What functionality does the ISE in Windows PowerShell 5.0 now have that was previously only
available in the console?
Answer: Windows PowerShell 5.0 now supports the Start-Transcript and Stop-Transcript
cmdlets. Support for these cmdlets was the most obvious difference between the ISE and the
console in previous versions.
Help files contain only syntax section—no Run Update-Help to download the complete help file
description or examples. content.
Cannot use Update-Help with computers From an Internet-connected computer, use Save-
not connected to the Internet. Help to download help content to a shared folder or
removable storage. On the unconnected computer,
run Update-Help and then specify the shared folder
or removable storage by using the –Source parameter.
Update-Help did not download all help. Update-Help will download help only for modules
that are located on your computer, in a path listed in
the PSModulePath environment variable, and only if
the module has the necessary metadata to tell
Update-Help where to find updated help files online.
Not all help might be available in all languages, and
Windows PowerShell will resort to en-US (US English)
help files if necessary.
Getting started with Windows PowerShell 1-13
Answer: Text and screen color are a matter of personal preference. However, some default ISE
colors can be difficult to see, such as the default light gray used for curly brackets and other
punctuation. Changing the colors can make these elements easier to see, helping you avoid
errors.
Question: What causes a horizontal scroll bar in the Windows PowerShell console window?
Answer: You will see a horizontal scroll bar when the screen buffer size is set to a value that is
greater than the window size.
Answer: You can use the Get-Module command with the -ListAvailable parameter to search for
available modules. The results of the Get-Module command include a partial list of commands.
This can help you identify possible nouns, or you can use the module name as a parameter in
Get-Command.
You can use the Get-Alias command to identify the Windows PowerShell command that runs
behind the scenes when you run a command that you used in cmd.exe or Linux environments
and the command works in Windows PowerShell.
Cmdlets for administration 2-1
Module 2
Cmdlets for administration
Contents:
Lesson 1: Active Directory administration cmdlets 2
Lesson 1
Active Directory administration cmdlets
Contents:
Question and Answers 3
Demonstration: Managing users and groups 3
Demonstration: Managing Active Directory objects 4
Cmdlets for administration 2-3
( ) Get
( ) Update
( ) New
( ) Remove
( ) Set
Answer:
( ) Get
(√) Update
( ) New
( ) Remove
( ) Set
Feedback:
The Update verb is not associated with the noun ADUser. There is no Update-ADUser cmdlet.
Question: The default value for the -ProtectedFromAccidentalDeletion parameter of New-
ADOrganizationalUnit is $true.
( ) True
( ) False
Answer:
(√) True
( ) False
Feedback:
The default value for -ProtectedFromAccidentalDeletion is $true.
2. In the search results, right-click Windows PowerShell, and then click Run as administrator.
3. In the Administrator: Windows PowerShell window, type the following command, and then press
Enter:
Note: The -Members parameter accepts a value that maps to several different properties.
Get-ADGroupMember HelpDesk
Set-ADUser Lara -StreetAddress "1530 Nowhere Ave." -City "Winnipeg" -State "Manitoba"
-Country "CA"
Get-ADGroup HelpDesk
Note: Note that the Name and DistinguishedName properties changed, but not the
SAMAccountName property.
2-6 Automating Administration with Windows PowerShell
Lesson 2
Network configuration cmdlets
Contents:
Question and Answers 7
Demonstration: Configuring network settings 7
Cmdlets for administration 2-7
Answer: You can use -InterfaceAlias or -InterfaceIndex to identify a network interface when using
*-NetIPAddress cmdlets.
Test-Connection LON-DC1
Note: Note the speed of the connection so that you can compare it to the speed after you
make changes.
Get-NetIPConfiguration
Note: Note the IP address, default gateway, and Domain Name System (DNS) server.
2. In the Administrator: Windows PowerShell window, type the following command, and then press
Enter:
3. In the Administrator: Windows PowerShell window, type the following command, and then press
Enter:
Get-NetIPConfiguration
Test-Connection LON-DC1
Lesson 3
Other server administration cmdlets
Contents:
Question and Answers 10
2-10 Automating Administration with Windows PowerShell
Answer: Before you can use Hyper-V cmdlets, at a minimum, you must install the Hyper-V
management module part of the Hyper-V feature.
Cmdlets for administration 2-11
Review Questions
Question: What command in the Windows PowerShell command-line interface can you use instead of
ping.exe?
Question: Name at least two ways in which you can create an Active Directory Domain Services (AD DS)
user account by using Windows PowerShell.
Answer: You can create a user account by using either the New-ADUser or the New-ADObject
cmdlet.
When I run the Get-Help command for a This means that only partial help is installed on your
cmdlet with the -Example parameter, I do not system. Run the Update-Help command or use the
see any examples. -Online parameter with Get-Help to force the
command to open web-based help in the browser.
I update the Windows PowerShell version on Verify that your current operating system supports
my system, but a new command does not the command. It is possible that the command
appear to do anything. depends on underlying changes to features.
2-12 Automating Administration with Windows PowerShell
Answer: Yes. A site named Default Web Site should be there. You can find the answer by
running the Get-Website command and viewing the output.
Working with the Windows PowerShell pipeline 3-1
Module 3
Working with the Windows PowerShell pipeline
Contents:
Lesson 1: Understanding the pipeline 2
Lesson 1
Understanding the pipeline
Contents:
Question and Answers 3
Demonstration: Viewing object members 3
Demonstration: Formatting pipeline output 4
Working with the Windows PowerShell pipeline 3-3
Answer: It depends on who wrote the command that produced the object. For most Microsoft
commands, the MSDN Library documents the output objects. Using the object’s type name in an
Internet search is frequently the fastest way to find existing documentation about an object.
Question: The Format-Wide cmdlet accepts the -AutoSize and -Wrap parameters.
( ) True
( ) False
Answer:
( ) True
(√) False
Feedback:
3. In the Administrator: Windows PowerShell window, type the following command, and then press
Enter:
Get-Service | Get-Member
4. In the Windows PowerShell console, type the following command, and then press Enter:
Get-Process | Get-Member
5. In the Windows PowerShell console, type the following command, and then press Enter:
Get-ChildItem | Get-Member
Note: Note the default value for the PSIsContainer property and for the other returned
members.
6. In the Windows PowerShell console, type the following command, and then press Enter:
7. In the Windows PowerShell console, type the following command, and then press Enter:
Note: Note the number of returned properties and their names. This time, many more
properties are returned.
Get-Service
2. In the console, type the following command, and then press Enter:
3. In the console, type the following command, and then press Enter:
4. In the console, type the following command, and then press Enter:
5. In the console, type the following command, and then press Enter:
Get-ADUser -Filter *
6. In the console, type the following command, and then press Enter:
Lesson 2
Selecting, sorting, and measuring objects
Contents:
Question and Answers 6
Demonstration: Sorting objects 6
Demonstration: Measuring objects 7
Demonstration: Selecting objects 7
Demonstration: Creating calculated properties 7
3-6 Automating Administration with Windows PowerShell
Answer: When you do not need the entire output of a command, selecting only the first rows
can improve performance. Select-Object can tell the previous commands that it requires no
more data. Some commands can then stop processing, thereby reducing the total amount of
time it takes Windows PowerShell to complete the task.
Get-Process
2. In the Administrator: Windows PowerShell window, type the following command, and then press
Enter:
3. In the console, type the following command, and then press Enter:
Note: Point out that Stopped appears before Running because the property is internally
stored as a number, with zero (Stopped) coming before 1 (Running).
4. In the console, type the following command, and then press Enter:
5. In the console, type the following command, and then press Enter:
6. In the console, type the following command, and then press Enter:
7. In the console, type the following command, and then press Enter:
Note: Users are sorted by column, and not by row. Also, any users created in earlier
demonstrations appear at the beginning of the list, because no value was set for the SurName
property when they were created.
Working with the Windows PowerShell pipeline 3-7
Get-Service | Measure-Object
2. In the console, type the following command, and then press Enter:
3. In the console, type the following command, and then press Enter:
2. In the console, type the following command, and then press Enter:
3. In the console, type the following command, and then press Enter:
4. In the console, type the following command, and then press Enter:
2. In the console, type the following command, and then press Enter:
3. In the console, type the following command, and then press Enter:
4. In the console, type the following command, and then press Enter:
Lesson 3
Filtering objects out of the pipeline
Contents:
Question and Answers 10
Demonstration: Filtering 10
3-10 Automating Administration with Windows PowerShell
Answer: This is obviously a personal opinion. The $PSItem variable is new in Windows
PowerShell 3.0, so experienced users frequently use $_ out of habit. The $_ variable is obviously
shorter and easier to type, but for many beginners, it is more visually confusing than $PSItem.
Both work the same way, and you will probably see both in various online examples, books, and
other resources. Many of the examples in the Windows PowerShell own help files still use $_.
Question: Is the following command the most efficient way to produce a list of services that have names
beginning with svc?
Demonstration: Filtering
Demonstration Steps
1. On LON-CL1, in the console, type the following command, and then press Enter:
2. In the console, type the following command, and then press Enter:
3. In the console, type the following command, and then press Enter:
4. In the console, type the following command, and then press Enter:
Lesson 4
Enumerating objects in the pipeline
Contents:
Question and Answers 12
Demonstration: Basic enumeration 12
Demonstration: Advanced enumeration 12
3-12 Automating Administration with Windows PowerShell
Answer: The command is functionally similar to the enumeration programming constructs that
many programming and scripting languages have. For example, in Microsoft Visual Basic, the
ForEach construct provides a similar purpose. Windows PowerShell does have a ForEach
scripting construct, although its syntax differs from that of the ForEach-Object command.
2. In the console, type the following command, and then press Enter:
2. In the console, type the following command, and then press Enter:
Lesson 5
Sending pipeline data as output
Contents:
Question and Answers 14
Demonstration: Exporting data 14
3-14 Automating Administration with Windows PowerShell
Answer: Many formats exist. The .xls and the .xlsx formats are common requests, although
Windows PowerShell does not contain a native command for reading or writing those formats.
Get-Process | ConvertTo-Html
Note: Because you used the verb ConvertTo, the data remains in Windows PowerShell and
displays on the screen.
2. In the console, type the following command, and then press Enter:
Note: You must use this two-step approach, because Windows PowerShell does not
provide an Export-Html command.
3. Open File Explorer, navigate to E:\ , and then open the Procs.html file in Internet Explorer.
4. In the console, type the following command, and then press Enter:
5. In File Explorer, navigate to E:\ , and then open the Procs.json file in Notepad.
6. In the console, type one of the following commands, and then press Enter:
7. In the console, type the following command, and then press Enter:
Notepad E:\Serv.csv
Note: Notice how some data, such as dependent services, are missing. That is because a
comma-separated values (CSV) file cannot appropriately show hierarchical data or nested objects.
8. In the console, type the following command, and then press Enter:
9. In the console, type the following command, and then press Enter:
Notepad E:\Serv.xml
Review Question
Question: The $_ and $PSItem variable names were used several times in this module. Why might you
decide to use one over the other?
Answer: Both are functionally the same. Windows PowerShell 3.0 introduced $PSItem as an
easier-to-read alternative to $_, so $PSItem is not available in earlier versions of Windows
PowerShell. Therefore, scripts that have to maintain backward compatibility must continue to use
$_. You are likely to see $_ in examples (such as in online articles or blogs) written by other
people for earlier versions, so you should remember both $_ and $PSItem.
In Windows PowerShell 3.0 or newer, the preceding five commands produce the same result: a list of
service names. As you explore Windows PowerShell, and especially as you read examples written by other
people or provided by your instructor, be aware that just one correct way to use Windows PowerShell
does not exist. Part of using Windows PowerShell is being able to understand many approaches,
arrangements of syntax, and techniques.
The $_ variable does not work. The $_ variable is a special placeholder and works
only in positions where Windows PowerShell is
programmed to look for it. Examples include the
script block used in a calculated property expression,
the filter script for Where-Object, and the script
block used for ForEach-Object.
The variable name $_ is confusing to read. You can use the $PSItem variable instead. This
variable was introduced in Windows PowerShell 3.0.
You can use $PSItem in the same positions as $_.
Working with the Windows PowerShell pipeline 3-17
Answer: The Select-Object command has an -ExcludeProperty parameter. Use it to list the one
property that you do not want to include, and use -Property * to include the remaining
properties.
Question: List the basic formatting commands, and explain why you might use each one.
Answer: Format-List allows you to view many properties for an object at one time. The
command truncates the property list when you also use Format-Table.
Format-Table creates output in a compact format that makes it is easier to view more than one
property for multiple objects. It also makes it possible to compare values among properties.
Format-Wide allows you to view many instances of a single property, like names, in as compact
a format as possible.
Answer: Answers will vary. However, remember that you will probably encounter both forms of
the syntax as you discover examples, such as those in books or blogs, written by other Windows
PowerShell users.
Answer: They seem to offer similar functionality. However, Select chooses the properties that
you want to include in your output, and can choose objects from the beginning or the end of the
collection. Where can also choose objects. However, it does so based on criteria that you
provide.
If you are familiar with any version of Structured Query Language, it might help to remember
that the SELECT keyword chooses columns, and the WHERE keyword chooses rows. The
Windows PowerShell commands have similar names because they have similar purposes.
Question: In the first task of this lab, were you able to achieve the goal without using the Where-Object
command?
Answer: You should have been able to. The Get-ADUser command has -Filter and -SearchBase
parameters that provide the filtering functionality that you needed. Using Where-Object would
have been inefficient and incorrect in this scenario.
3-18 Automating Administration with Windows PowerShell
Answer: Answers will vary. However, remember that you will probably encounter both forms of
the syntax as you discover examples, such as in books or blogs, that other Windows PowerShell
users have written.
Answer: Yes. Both commands have a -Delimiter parameter that changes the delimiter used for
the file. Use "`t" to specify a tab character, and note that the quotation marks (" ") are required.
Question: The HTML data produced by ConvertTo-Html looks very plain. The HTML standard offers a
way to specify visual styles for an HTML document. This is known as Cascading Style Sheets (CSS). Does
the command offer a way to attach a style sheet?
Answer: Yes. You can either embed a style sheet by providing the appropriate HTML and CSS
code to the -Head parameter or attach an external style sheet by using the -CssUri parameter.
Understanding how the pipeline works 4-1
Module 4
Understanding how the pipeline works
Contents:
Lesson 1: Passing pipeline data 2
Lesson 1
Passing pipeline data
Contents:
Question and Answers 3
Demonstration: Passing data by using ByValue 3
Demonstration: Passing data ByPropertyName 3
Understanding how the pipeline works 4-3
Answer: Commands that use the noun Object work with any kind of input. Therefore, each of
them defines a parameter named –InputObject. That parameter receives any kind of object from
the pipeline, and therefore, it accepts input of the type Object or PSObject from the pipeline by
using ByValue.
2. In the search results, right-click Windows PowerShell ISE, and then select Run as administrator.
3. In the Administrator: Windows PowerShell ISE window, type the following command, and then
press Enter:
Get-Service | Get-Member
6. In the Help window, show that the –InputObject parameter accepts objects of the type
ServiceController from the pipeline by using ByValue.
You should have determined that the objects that the first command, Get-Service, produced will
attach to the –InputObject parameter of the second command, Stop-Service.
2. In the search results, right-click Windows PowerShell on the taskbar, and then select Run as
administrator.
3. In the Administrator: Windows PowerShell window, type the following command, and then press
Enter:
Point out the “Cannot validate argument on parameter ‘ComputerName’” error. This means that the
object that Get-ADComputer returns does not have a ComputerName property and no other
property name matches a parameter name that accepts pipeline input.
4-4 Automating Administration with Windows PowerShell
4. In the console window, type the following command, and then press Enter:
Point out the members of Get-ADComputer and focus on the Name property.
5. In the console window, type the following command, and then press Enter:
Review the parameters and focus on the parameters that accept either ByValue or ByPropertyName
pipeline input and that two of them accept ByPropertyName values. Call out the ComputerName
parameter that maps to the Name property of Get-ADComputer.
6. In the console window, type the following command, and then press Enter:
Remind students that they learned how to create a calculated value in Module 3, “Working with the
Windows PowerShell pipeline .” Reinforce that $PSItem is a special variable that represents the object
that pipes to Select-Object.
Understanding how the pipeline works 4-5
Lesson 2
Advanced techniques for passing pipeline data
Contents:
Question and Answers 6
Demonstration: Overriding the pipeline 6
Demonstration: Using parenthetical commands 6
Demonstration: Expanding property values 7
4-6 Automating Administration with Windows PowerShell
• In some cases, a parenthetical command can be more efficient than the piped command. For
example, if a parameter can take multiple values as input, it is faster to pass those with a
parenthetical command than it is to pipe that input into the command individually.
• You can use parenthetical commands to pass data to parameters that do not normally take
piped input.
3. Click Start, type Notepad, and then open the Notepad app.
4. In the Administrator: Windows PowerShell window, type the following command, and then press
Enter:
6. In the console, type the following command, and then press Enter:
7. Review the error, and then discuss how using the –Name parameter causes an error.
2. In the console, type the following command, and then press Enter:
Note that a prompt to enter users appears. Press Enter. You will see an error because no member was
specified.
Understanding how the pipeline works 4-7
3. In the console, type the following command, and then press Enter:
4. In the console, type the following command, and then press Enter:
3. In the Administrator: Windows PowerShell ISE window, type the following command in Windows
PowerShell ISE:
Get-ADComputer –Filter *
This retrieves a list of computer objects. These are full objects with several properties each.
4. In the Script pane, type the following command, and then press Enter:
This will return an error. Explain that your goal is to display a list of services that are running on every
computer in the domain.
5. In the Console pane, type the following command, and then press Enter:
Explain that the command produces objects of the type ADComputer, as shown by the output of
Get-Member.
6. In the Console pane, type the following command, and then press Enter:
In the Help window, explain that the –ComputerName parameter accepts objects of the type String.
Go back to the Script pane, and then explain that the parenthetical command is producing objects
that are not of the type String. Therefore, the command will not work. The parenthetical command is
not producing the kind of object that the parameter requires.
7. In the Console pane, type the following command, and then press Enter:
Explain that this does select only the Name property. The –ComputerName parameter wants a
name, and the Name property contains a name.
4-8 Automating Administration with Windows PowerShell
8. In the Console pane, type the following command, and then press Enter:
Explain that the output of Select-Object in this example is still an ADComputer object. It is not a
string. In the Console pane, run the following command, and then press Enter:
Explain that –ExpandProperty accepts a single property name, and it extracts the contents of that
property.
9. In the Console pane, type the following command, and then press Enter:
Explain that by using –ExpandProperty, the output of Select-Object is now a string. That is the kind
of object the –ComputerName parameter expects.
10. In the Script pane, change the parenthetical command to the following command:
Explain that this will retrieve every computer object from the domain and extract the contents of their
Name properties as a string. Those strings will be given to the –ComputerName parameter.
11. Press F5 to run the command. As per your original goal that was outlined in step 3, it should display a
list of services from every computer in the domain. You might see errors if every computer is not
online or available. However, the command will try to contact each one.
Understanding how the pipeline works 4-9
Review Question
Question: Because Windows PowerShell handles pipeline input binding invisibly, it can be difficult to
troubleshoot. Are there any tools that can help you troubleshoot pipeline input?
Answer: Yes. The built-in Trace-Command command can analyze a command as it runs and
display information about how data attaches to each parameter. Read the Help file, especially the
examples, for this command to learn more details.
Answer: It depends completely on what the developer of the command decided. You cannot
change pipeline acceptance except to rewrite the command. In the case of a cmdlet, that would
require you to have the original source code.
Question: Do you ever have to rely on pipeline input? Could you just rely on parenthetical commands?
Answer: You could just rely on parenthetical commands. However, they can become complex
and difficult to read. For example, consider this command that uses pipeline input:
Module 5
Using PSProviders and PSDrives
Contents:
Lesson 1: Using PSProviders 2
Lesson 1
Using PSProviders
Contents:
Question and Answers 3
Demonstration: Viewing PSProvider help 3
Using PSProviders and PSDrives 5-3
Answer: Microsoft has created PSProviders for Active Directory Domain Services (AD DS),
Microsoft SQL Server, Microsoft Internet Information Services (IIS), and many other products and
technologies. Independent software vendors (ISVs) can also create add-in PSProviders.
2. In the results list, right-click Windows PowerShell and then click Run as administrator.
3. In the Windows PowerShell console, type the following command, and then press Enter:
Get-PSProvider
4. In the console, type the following command, and then press Enter:
Import-Module ActiveDirectory
5. In the console, type the following command, and then press Enter:
Get-PSProvider
6. In the console, type the following command, and then press Enter:
Get-Help Registry
5-4 Automating Administration with Windows PowerShell
Lesson 2
Using PSDrives
Contents:
Question and Answers 5
Demonstration: Managing the file system 5
Demonstration: Managing the registry 5
Using PSProviders and PSDrives 5-5
Answer: Dynamic parameters are parameters that are available only under certain conditions.
PSProviders sometimes define dynamic parameters for certain cmdlets to help manage the
underlying technology.
Cd C:\
2. In the console, type the following command, and then press Enter:
Set-Location C:\Windows
3. In the console, type the following command, and then press Enter:
4. In the console, type the following command, and then press Enter:
Dir WINDIR:
5. In the console, type the following command, and then press Enter:
Get-ChildItem WINDIR:
6. In the console, type the following command, and then press Enter:
Set-Location HKLM:\Software
2. In the console, type the following command, and then press Enter:
Get-ChildItem
3. In the console, type the following command, and then press Enter:
4. In the console, type the following command, and then press Enter:
5. In the console, type the following command, and then press Enter:
A PSDrive that was present in Windows Windows PowerShell always starts with the same
PowerShell is no longer present. default PSDrive mappings. If you create a new
mapping that is not persistent, the mapping will
not exist in other Windows PowerShell sessions
and will not be present in any new Windows
PowerShell sessions. You must recreate the
mapping in each new session that you open.
5-8 Automating Administration with Windows PowerShell
Answer: The FileSystem and WSMan providers support the use of alternative credentials. Run
Get-PSProvider to see that information, which is indicated by the Credentials capability. Load
the ActiveDirectory module to see that the ActiveDirectory provider supports alternative
credentials.
Question: Windows PowerShell 3.0 and newer can make one kind of PSDrive visible in File Explorer.
What kind of drive is that, and how do you make it visible?
Answer: When you run New-PSDrive, the –Persistent parameter will make a drive visible in File
Explorer. This works correctly only when the drive name is a single letter and is mapped to a
FileSystem location.
Querying management information by using CIM and WMI 6-1
Module 6
Querying management information by using CIM and WMI
Contents:
Lesson 1: Understanding CIM and WMI 2
Lesson 1
Understanding CIM and WMI
Contents:
Question and Answers 3
Resources 3
Demonstration: Finding documentation for classes 3
Querying management information by using CIM and WMI 6-3
Answer: The only situation occurs when you have to query a remote computer and you do not
want to create a CIM session that uses the DCOM protocol.
Resources
Architecture and technologies
3. Explain that this Microsoft Developer Network (MSDN) webpage is the documentation page for the
class. Review some of the class properties.
6-4 Automating Administration with Windows PowerShell
Lesson 2
Querying data by using CIM and WMI
Contents:
Question and Answers 5
Resources 5
Demonstration: Listing local repository namespaces by using WMI 5
Demonstration: Listing and sorting the classes from a namespace 5
Demonstration: Querying class instances 6
Demonstration: Using CIMSession objects 6
Querying management information by using CIM and WMI 6-5
Answer: If you query a computer multiple times in a short period of time, a CIM session offers
much better performance than an ad-hoc connection.
Resources
Listing classes
Reference Links: A graphical WMI Explorer tool, written in a Windows PowerShell script, is
available at https://aka.ms/cu41zp. This tool can make it easier to explore the WMI classes that
are available on a particular computer.
2. In the Windows PowerShell console, type the following command, and then press Enter:
3. Note the root\CIMV2 namespace and the root\SecurityCenter2 namespace. You will use these in
the next demonstration.
2. Observe the values returned. Point out the CimClassName, CimClassMethods, and
CimClassProperties column names and the values returned in each row.
3. In the Windows PowerShell console, type the following command, and then press Enter:
Explain that the class names starting with two underscores (__) are system classes. You can typically
ignore system classes.
4. In the Windows PowerShell console, type the following command, and then press Enter:
Explain that an alphabetical list is useful when you have to validate a guess about a class name. For
example, if you think a class named Win32_Network might be useful, you can more easily discover
whether the class exists by using an alphabetical list.
6-6 Automating Administration with Windows PowerShell
5. To find all the classes in the root\CIMv2 namespace that have network in the class name, type the
following command in the Windows PowerShell console, and then press Enter:
Note that this technique cannot search class descriptions, because that information is not stored in
the repository.
2. In the Windows PowerShell console, type the following command, and then press Enter:
3. In the Windows PowerShell console, type the following command, and then press Enter:
4. In the Windows PowerShell console, type the following command, and then press Enter:
2. In the Windows PowerShell console, type the following command, and then press Enter:
3. In the Windows PowerShell console, type the following command, and then press Enter:
$s | Remove-CimSession
Querying management information by using CIM and WMI 6-7
Lesson 3
Making changes by using CIM and WMI
Contents:
Question and Answers 8
Demonstration: Finding methods and documentation 8
Demonstration: Invoking methods of repository objects 9
6-8 Automating Administration with Windows PowerShell
Answer: ForEach-Object does not include the -WhatIf or the -Confirm parameter. When you use
this command to invoke a method, the method will run, but you will not have any way to test
your command.
3. Try the same thing by using CIM. In the Windows PowerShell console, type the following command,
and then press Enter:
Note that although you get all the methods, the information is not as detailed as what you get from
Get-WmiObject.
4. Use the preceding Get-CimClass command, but pipe the results to Get-Member. In the Windows
PowerShell console, type the following command, and then press Enter:
Note that this does not return the methods that the previous CIM and WMI commands did, but it
returns five additional methods. These methods are from the
Microsoft.Management.Infrastructure.CimClass namespace and not from Win32_Service.
5. In a web browser on the host computer, go to the Bing website (or your preferred search engine).
8. On the webpage, scroll down to the “Methods” section, and then click Change.
appear.
Explain that this method has 11 parameters. Review the parameters with the class.
Querying management information by using CIM and WMI 6-9
2. On the taskbar, in the Search box, type Paint, click the Paint icon in the returned list, and then verify
that the Paint application opens.
3. In the Windows PowerShell console or Windows PowerShell ISE, type the following command, and
then press Enter:
Review Question
Question: What do you think is the most difficult part about working with WMI and CIM?
Answer: Discovering the class that you want is the most difficult part about these technologies.
Without a central directory and with inconsistent documentation, finding the class that will let
you achieve a specific task might be very difficult and time consuming. Many administrators rely
on Internet search engines and Internet discussion forums to find classes.
Tools
Tool Description Where to find it
You get an RPC server not found error This error indicates that either the computer cannot
when you use WMI commands. be reached on the network or the computer has a
local firewall that is preventing RPC connections.
You get errors when you use CIM to WS-MAN has specific requirements for connectivity
connect to a remote computer by using the that include mutual authentication. Between trusted
WS-MAN protocol. computers in a domain, mutual authentication is
automatic. Outside a domain, additional configuration
is required. Module 10, “Administering remote
computers,” provides more details about the
additional configuration steps.
You get an access denied error when Only the members of a computer’s local
attempting to connect to a remote Administrators group can remotely query information
computer. from that computer. You need to either open
Windows PowerShell by using an appropriate
administrator user account or provide an alternative
credential when querying.
Querying management information by using CIM and WMI 6-11
Answer: The class forces Windows Installer to revalidate all installed packages. On computers
that have many installed packages, the validation process might take a long time to complete
and might have a negative effect on performance.
Question: What are the main differences between WMI and CIM?
Answer: Both query the same repository, so both can return the same information and perform
the same tasks. The only difference is the protocol each one uses to communicate with remote
computers. WMI uses an earlier implementation of the Distributed Management Task Force
(DMTF) repository, whereas CIM is fully compliant with the current DMTF standard.
Working with variables, arrays, and hash tables 7-1
Module 7
Working with variables, arrays, and hash tables
Contents:
Lesson 1: Using variables 2
Lesson 1
Using variables
Contents:
Question and Answers 3
Demonstration: Assigning a variable type 3
Working with variables, arrays, and hash tables 7-3
Answer: You need to assign a variable type when Windows PowerShell cannot accurately
determine the correct variable type. One common issue is non-string data that is enclosed in
quotes. Any text enclosed in quotes is interpreted as a string by default. If you want the text in
quotes to be interpreted as another variable type such as DateTime, then you need to specify the
variable type.
2. In the results list, right-click Windows PowerShell and then click Run as administrator.
3. To set the value of $num1 to 5, at the Windows PowerShell prompt, type the following command,
and then press Enter:
$num1 = 5
4. To display the value of $num1, type the following command, and then press Enter:
$num1
5. To set the value of $logFile to be C:\Logs\Log.txt, type the following command, and then press Enter:
$logFile = "C:\Logs\Log.txt"
6. To view the value of $logFile, type the following command, and then press Enter:
$logFile
7. To set the value of $service to the W32Time service, type the following command, and then press
Enter:
8. To display the value of $service, type the following command, and then press Enter:
$service
9. To display $logFile as part of a text message on screen, type the following command, and then press
Enter:
10. To view all of the properties of the service object stored in $service, type the following command, and
then press Enter:
$service | Format-List *
11. To view the Status property of $service, type the following command, and then press Enter:
$service.status
7-4 Automating Administration with Windows PowerShell
12. To view the Name and Status properties of $service, type the following command, and then press
Enter:
13. To view the variables in memory, type the following command, and then press Enter:
Get-Variable
14. To view the variables in memory, type the following command, and then press Enter:
Get-ChildItem Variable:
15. To view the variable type of $num1, type the following command, and then press Enter:
$num1.GetType()
16. To view the variable type of $logFile, type the following command, and then press Enter:
$logFile.GetType()
17. To view the variable type of $service, type the following command, and then press Enter:
$service.GetType()
18. To view the properties and methods of $service, type the following command, and then press Enter:
$service | Get-Member
19. To set the value of $num2 as a string of 5, type the following command, and then press Enter:
$num2 = "5"
20. To set the value of $num3 as a 32-bit integer of 5, type the following command, and then press Enter:
[Int]$num3 = "5"
21. To verify the variable type of $num2, type the following command, and then press Enter:
$num2.GetType()
22. To verify the variable type of $num3, type the following command, and then press Enter:
$num3.GetType()
23. To set $date1 as a string, type the following command, and then press Enter:
24. To set $date2 as a DateTime type, type the following command, and then press Enter:
25. To verify the variable type of $date1, type the following command, and then press Enter:
$date1.GetType()
Working with variables, arrays, and hash tables 7-5
26. To verify the variable type of $date2, type the following command, and then press Enter:
$date2.GetType()
27. To attempt to convert a string to a 32-bit integer, type the following command, and then press Enter:
28. To view how variable types can convert during operations, type the following command, and then
press Enter:
$num2 + $num3
29. To view how variable types can convert during operations, type the following command, and then
press Enter:
$num3 + $num2
30. To view how variable types can fail to convert during operations, type the following command, and
then press Enter:
$num3 + $logFile
Lesson 2
Manipulating variables
Contents:
Question and Answers 7
Resources 7
Demonstration: Manipulating strings 7
Demonstration: Manipulating dates 8
Working with variables, arrays, and hash tables 7-7
Answer: The Get-Member cmdlet identifies the properties and methods that are available for a
specific variable type. You need this information to identify which actions are available by using
methods. You also use this information as a starting point for research on how to use the
methods.
Resources
Additional Reading: For more information on .NET Framework variable types, refer to
“System Namespace” at https://aka.ms/krlgav.
2. To set $logFile with a value, at the Windows PowerShell prompt, type the following command, and
then press Enter:
$logFile = "C:\Logs\log.txt"
3. To identify whether $logFile contains the text C:, type the following command, and then press Enter:
$logFile.Contains("C:")
4. To identify whether $logFile contains the text D:, type the following command, and then press Enter:
$logFile.Contains("D:")
5. To insert the text \MyScript at character 7, type the following command, and then press Enter:
$logFile.Insert(7,"\MyScript")
6. To verify that the value stored in $logFile has not changed, type the following command, and then
press Enter:
$logFile
7. To update the value of $logFile, type the following command, and then press Enter:
$logFile=$logFile.Insert(7,"\MyScript")
8. To verify that the value of $logFile has changed, type the following command, and then press Enter:
$logFile
9. To replace .txt with .htm, type the following command, and then press Enter:
$logFile.Replace(".txt",".htm")
7-8 Automating Administration with Windows PowerShell
10. To split the value of $logFile at the \ character, type the following command, and then press Enter:
$logFile.Split("\")
11. To view only the last item from the split, type the following command, and then press Enter:
12. To convert the value to uppercase letters, type the following command, and then press Enter:
$logFile.ToUpper()
13. To convert the value to lowercase letters, type the following command, and then press Enter:
$logFile.ToLower()
$date = Get-Date
3. To display the value of $date, at the Windows PowerShell prompt, type the following command, and
then press Enter:
$date
4. To display the Hour property of $date, type the following command, and then press Enter:
$date.Hour
5. To display the Minute property of $date, type the following command, and then press Enter:
$date.Minute
6. To display the Day property of $date, type the following command, and then press Enter:
$date.Day
7. To display the DayOfWeek property of $date, type the following command, and then press Enter:
$date.DayOfWeek
8. To display the Month property of $date, type the following command, and then press Enter:
$date.Month
9. To display the Year property of $date, type the following command, and then press Enter:
$date.Year
Working with variables, arrays, and hash tables 7-9
10. To add 100 days to $date, type the following command, and then press Enter:
$date.AddDays(100)
11. To subtract 60 days from $date, type the following command, and then press Enter:
$date.AddDays(-60)
12. To display $date as a long date string, type the following command, and then press Enter:
$date.ToLongDateString()
13. To display $date as a short date string, type the following command, and then press Enter:
$date.ToShortDateString()
14. To display $date as a long time string, type the following command, and then press Enter:
$date.ToLongTimeString()
15. To display $date as a short time string, type the following command, and then press Enter:
$date.ToShortTimeString()
Lesson 3
Manipulating arrays and hash tables
Contents:
Question and Answers 11
Demonstration: Manipulating arrays and arraylists 11
Demonstration: Manipulating hash tables 12
Working with variables, arrays, and hash tables 7-11
Answer: The arrays that Windows PowerShell creates by default are fixed-size arrays.
Consequently, you cannot use the add or remove methods. This means that arrays have relatively
low performance when you work with large datasets.
If instead you choose to create an arraylist, they do not have a fixed size. Therefore, you can add
or remove items from the arraylist and have better performance for large datasets.
2. To set $computers to be an array of strings, at the Windows PowerShell prompt, type the following
command, and then press Enter:
$computers = "LON-DC1","LON-SRV1","LON-CL1"
3. To set $users to be an array of user objects, type the following command, and then press Enter:
4. To view the contents of the $computers array, type the following command, and then press Enter:
$computers
5. To view the contents of the $users array, type the following command, and then press Enter:
$users
6. To view the number of items in $users, type the following command, and then press Enter:
$users.count
7. To view the user object at index 125 of $users, type the following command, and then press Enter:
$users[125]
8. To view the properties and methods available for the items in $computers, type the following
command, and then press Enter:
$computers | Get-Member
9. To view the properties and methods available for the items in $users, type the following command,
and then press Enter:
$users | Get-Member
10. To view the UserPrincipalName property for a user object in the array, type the following command,
and then press Enter:
$users[125].UserPrincipalName
7-12 Automating Administration with Windows PowerShell
11. To add an item to $computers, type the following command, and then press Enter:
$computers += "LON-SRV2"
12. To verify that the item was added, type the following command, and then press Enter:
$computers
13. To create an arraylist containing user objects, type the following command, and then press Enter:
14. To identify whether $usersList has a fixed size, type the following command, and then press Enter:
$usersList.IsFixedSize
15. To view the number of items in $arrayList, type the following command, and then press Enter:
$usersList.count
16. To view a single item in $arrayList, type the following command, and then press Enter:
$usersList[125]
17. To remove an item in $arrayList, type the following command, and then press Enter:
$usersList.RemoveAt(125)
18. To verify that the item count is reduced by one, type the following command, and then press Enter:
$usersList.count
19. To verify that the item at index 125 has changed, type the following command, and then press Enter:
$usersList[125]
2. To create a hash table with the names of users and a department for each, at the Windows
PowerShell prompt, type the following command, and then press Enter:
$users = @{"Lara"="IT";"Peter"="Managers";"Sang"="Sales"}
3. To view the contents of the hash table, type the following command, and then press Enter:
$users
4. To view the department for a single user, type the following command, and then press Enter:
$users.Lara
Working with variables, arrays, and hash tables 7-13
5. To update the department for a user, type the following command, and then press Enter:
$users.Sang = "Marketing"
6. To verify that the department was updated, type the following command, and then press Enter:
$users
7. To add a new user, type the following command, and then press Enter:
$users.Add("Tia","Research")
8. To remove a user, type the following command, and then press Enter:
$users.Remove("Sang")
9. To verify the added and removed users, type the following command, and then press Enter:
$users
10. To create a new hash table for a calculated property, type the following command, and then press
Enter:
$prop = @{n="Size(KB)";e={$_.Length/1KB}}
11. To view the hash table, type the following command, and then press Enter:
$prop
12. To view the name and size of the files in C:\Windows, type the following command, and then press
Enter:
13. To view the size of files by using the calculated properly, type the following command, and then press
Enter:
Answer: If you did not define the variable as an arraylist, it would be automatically created as an
array. You cannot use the Add() or Remove() method with an array because it has a fixed size.
You must define the variable as an arraylist to be able to add and remove items.
Question: You have placed the value “February 20, 2018” into a variable. What type of variable will it be?
Answer: Text enclosed in quotes is interpreted as a string unless you specify the type of variable
it should be. For example: [DateTime]$date=”February 20, 2018”.
Working with variables, arrays, and hash tables 7-15
Answer: When you query data and place it in a variable, the data in the variable is a snapshot in
time. There is no mechanism to dynamically update the data in the variable. If you want the data
in the variable to be updated, you need to query the data again.
Question: In Exercise 1, you replaced C: with D: in the variable $logPath. Why is it better to include colon
than simply replace C with D?
Answer: In a file path, the colon character only appears once. By including the colon as part of
the text that is replaced, you ensure that only the drive letter is updated. If you did not include
the colon and if the path contained the character C at any other location, it would be replaced as
well.
Basic scripting 8-1
Module 8
Basic scripting
Contents:
Lesson 1: Introduction to scripting 2
Lesson 1
Introduction to scripting
Contents:
Resources 3
Demonstration: Setting the script execution policy 3
Demonstration: Digitally signing a script 4
Basic scripting 8-3
Resources
Modifying scripts
Additional Reading: For more information about creating a NuGet feed, refer to “Hosting
your own NuGet feeds” at https://aka.ms/vm0ys1.
Additional Reading: For more information about all of the PowerShellGet cmdlets, refer to
“PowerShellGet cmdlet reference” at https://aka.ms/tykgas.
4. Click Yes to confirm that you want to change the file extension.
5. Double-click HelloWorld.ps1.
6. Close Notepad.
7. Right-click HelloWorld.ps1, and then click Run with PowerShell. Close PowerShell.
10. To change the prompt location, at the Windows PowerShell prompt, type the following command,
and then press Enter:
Set-Location E:\Mod08\Democode
11. To verify that HelloWorld.ps1 is in the current directory, at the Windows PowerShell prompt, type
the following command, and then press Enter:
Get-ChildItem HelloWorld.ps1
8-4 Automating Administration with Windows PowerShell
12. To run HelloWorld.ps1 by using the full path, at the Windows PowerShell prompt, type the following
command, and then press Enter:
E:\Mod08\Democode\HelloWorld.ps1
13. To verify you cannot run HelloWorld.ps1 without specifying a path, at the Windows PowerShell
prompt, type the following command, and then press Enter:
HelloWorld.ps1
14. To run HelloWorld.ps1 in the current directory, at the Windows PowerShell prompt, type the
following command, and then press Enter:
.\HelloWorld.ps1
15. To view the current execution policy, at the Windows PowerShell prompt, type the following
command, and then press Enter:
Get-ExecutionPolicy
16. To prevent all scripts from running, at the Windows PowerShell prompt, type the following command,
and then press Enter:
Set-ExecutionPolicy Restricted
18. To verify that all scripts are blocked, at the Windows PowerShell prompt, type the following
command, and then press Enter:
.\HelloWorld.ps1
19. To allow all scripts to be run, at the Windows PowerShell prompt, type the following command, and
then press Enter:
Set-ExecutionPolicy Unrestricted
3. In the Add or Remove Snap-ins window, click Certificates, and then click Add.
4. In the Certificates snap-in dialog box, click My user account, and then click Finish.
5. In the Add or Remove Snap-ins window, click OK.
6. In the MMC console, expand Certificates - Current User, and then click Personal.
7. Right-click Personal, point to All Tasks, and then click Request New Certificate.
8. In the Certificate Enrollment wizard, on the Before You Begin page, click Next.
Basic scripting 8-5
9. On the Select Certificate Enrollment Policy page, click Active Directory Enrollment Policy, and
then click Next.
10. On the Request Certificates page, select the Adatum Code Signing check box, and then click
Enroll.
11. On the Certificate Installation Results page, click Finish.
12. In the MMC console, expand Personal, and then click Certificates to verify that the new code
signing certificate is present.
13. Close the MMC console, and then click No at the prompt to save the console settings.
2. To place the code signing certificate in a variable, at the Windows PowerShell prompt, type the
following command, and then press Enter:
3. To digitally sign a script, at the Windows PowerShell prompt, type the following command, and then
press Enter:
Lesson 2
Scripting constructs
Contents:
Demonstration: Using a ForEach loop 7
Demonstration: Using the If construct 7
Demonstration: Using the Switch construct 7
Basic scripting 8-7
6. Press F5 to run the script, and then click Yes to save the script.
6. Press F5 to run the script, and then click Yes to save the script.
8. Press F5 to run the script, and then click Yes to save the script.
9. In line 1, update the value of $computer to SEA-RDP.
10. Press F5 to run the script, and then click Yes to save the script.
Lesson 3
Importing data from files
Contents:
Demonstration: Importing data 9
Basic scripting 8-9
2. To retrieve data from a text file, at the Windows PowerShell prompt, type the following command,
and then press Enter:
Get-Content E:\Mod08\Democode\computers.txt
3. To place data from a text file into an array, at the Windows PowerShell prompt, type the following
command, and then press Enter:
4. To display the number of items in the $computers array, at the Windows PowerShell prompt, type the
following command, and then press Enter:
$computers.count
5. To display the items in the $computers array, at the Windows PowerShell prompt, type the following
command, and then press Enter:
$computers
6. To import CSV data, at the Windows PowerShell prompt, type the following command, and then
press Enter:
Import-Csv E:\Mod08\Democode\users.csv
7. To import CSV data into an array, at the Windows PowerShell prompt, type the following command,
and then press Enter:
8. To display the count of items in the array, at the Windows PowerShell prompt, type the following
command, and then press Enter:
$users.count
9. To display the first item in the array, at the Windows PowerShell prompt, type the following
command, and then press Enter:
$users[0]
10. To display the property named First for the item, at the Windows PowerShell prompt, type the
following command, and then press Enter:
$users[0].First
11. To import data from an XML file, at the Windows PowerShell prompt, type the following command,
and then press Enter:
Import-Clixml E:\Mod08\Democode\users.xml
8-10 Automating Administration with Windows PowerShell
12. To import XML data into an array, at the Windows PowerShell prompt, type the following command,
and then press Enter:
13. To view the number of items in the array, at the Windows PowerShell prompt, type the following
command, and then press Enter:
$usersXml.count
14. To view the first item in the array, at the Windows PowerShell prompt, type the following command,
and then press Enter:
$usersXml[0]
15. To view the properties for the items in the array, at the Windows PowerShell prompt, type the
following command, and then press Enter:
$usersXml | Get-Member
Answer: The format of the data should be the primary consideration. You choose the cmdlet to
match the type of data that is being imported. If you have a choice of data formats, you can
select the format that you are most comfortable with or is easiest to work with.
Question: Why is the ForEach construct used more often than the For construct?
Answer: Many Windows PowerShell scripts work on a set of data that is obtained from a query
or an imported file. Those data sets are of an unknown size, which is simpler to manage by using
ForEach. The For construct is typically used only when an action is being performed a specific
number of times.
8-12 Automating Administration with Windows PowerShell
Answer: A code signing certificate from an internal certification authority will only be trusted by
internal clients. If you are signing scripts that will be used outside your organization, you should
get the certificate from a third-party certification authority.
Question: In Exercise 2, you configured the ipPhone attribute for a group of test users. How would you
update that script for a larger set of users as the solution is deployed to the rest of the organization?
Answer: The script in Exercise 2 modified the ipPhone attribute for members of the
IPPhoneTest group. When this functionality is being deployed to the remainder of the
organization, the query for users will need to be expanded. For example, the script could be
modified to work for individual organizational units as the new system is deployed to each
department.
Advanced scripting 9-1
Module 9
Advanced scripting
Contents:
Lesson 1: Accepting user input 2
Lesson 1
Accepting user input
Contents:
Question and Answers 3
Demonstration: Obtaining user input 3
Demonstration: Obtaining user input by using parameters 4
Advanced scripting 9-3
Answer: Assigning a default value ensures that a parameter has a value. This ensures that your
script does not generate an error when that value is missing. However, not all parameters are
suitable for a default value. For example, a default value is not useful for a parameter that
specifies a remote computer because a remote computer name is unpredictable.
2. To obtain user input by using Read-Host, at the Windows PowerShell prompt, type the following
command, and then press Enter. At the prompt provide a number for the days:
3. To view the data obtained by Read-Host, at the Windows PowerShell prompt, type the following
command, and then press Enter:
$days
4. To obtain a credential, at the Windows PowerShell prompt, type the following command, and then
press Enter:
$cred = Get-Credential
5. To display the credential information, at the Windows PowerShell prompt, type the following
command, and then press Enter:
$cred | Format-List
6. To store the credential in a file, at the Windows PowerShell prompt, type the following command,
and then press Enter:
7. To view the content of the file, at the Windows PowerShell prompt, type the following command, and
then press Enter:
Get-Content E:\Mod09\Democode\cred.xml
8. To display a list of computer accounts in Out-GridView, at the Windows PowerShell prompt, type the
following command, and then press Enter:
10. To allow a single section in the Out-GridView window, at the Windows PowerShell prompt, type the
following command, and then press Enter:
12. To display the selected object, at the Windows PowerShell prompt, type the following command, and
then press Enter:
$computer
2. To rename a text file to a script file, at the Windows PowerShell prompt, type the following command,
and then press Enter:
5. In the Open window, in the address bar, type E:\Mod09\Democode and press Enter.
6. Click 10961C_Mod09_Demo02.ps1 and click Open.
7. Review the code and leave Windows PowerShell ISE open.
8. To set the current directory, at the Windows PowerShell prompt, type the following command, and
then press Enter:
Set-Location E:\Mod09\Democode
9. To pass values to the script by position, at the Windows PowerShell prompt, type the following
command, and then press Enter:
10. To pass values to the script by parameter name, at the Windows PowerShell prompt, type the
following command, and then press Enter:
11. To view the results when no parameter data is provided, at the Windows PowerShell prompt, type the
following command, and then press Enter:
.\10961C_Mod09_Demo02.ps1
12. In Windows PowerShell ISE, on line 2, after $ComputerName, type =(Read-Host “Enter computer
name”).
15. To view the results when no parameter data is provided, at the Windows PowerShell prompt, type the
following command, and then press Enter:
.\10961C_Mod09_Demo02.ps1
16. When prompted for a computer name, type LON-DC1, and then press Enter.
17. Close Windows PowerShell ISE and the Windows PowerShell prompt.
9-6 Automating Administration with Windows PowerShell
Lesson 2
Overview of script documentation
Contents:
Question and Answers 7
Demonstration: Adding comments to a script 7
Demonstration: Adding help information to a script 8
Advanced scripting 9-7
Answer: Comments are useful for other administrators who are trying to interpret your script,
and they are also useful for you. If you have not edited a script for an extended period,
comments help you understand what your thought process was during development.
2. To rename a text file to a script file, at the Windows PowerShell prompt, type the following command,
and then press Enter:
5. In the Open window, in the address bar, type E:\Mod09\Democode and press Enter.
6. Click 10961C_Mod09_Demo03.ps1 and click Open.
7. In Windows PowerShell ISE, review the code.
8. To set the current directory, at the Windows PowerShell prompt, type the following command, and
then press Enter:
Set-Location E:\Mod09\Democode
9. To view the script output, at the Windows PowerShell prompt, type the following command, and then
press Enter:
.\10961C_Mod09_Demo03.ps1
12. To verify that the script output has not changed, at the Windows PowerShell prompt, type the
following command, and then press Enter:
.\10961C_Mod09_Demo03.ps1
.\10961C_Mod09_Demo03.ps1
17. Close Windows PowerShell ISE and the Windows PowerShell prompt.
9-8 Automating Administration with Windows PowerShell
2. To rename a text file to a script file, at the Windows PowerShell prompt, type the following command,
and then press Enter:
4. In Windows PowerShell ISE, click the File menu and click Open.
5. In the Open window, in the address bar, type E:\Mod09\Democode and press Enter.
8. In the Open window, in the file type box, select Text Files (*.txt), click
10961C_Mod09_Demo04_Help.txt and click Open.
9. To copy the text, press Ctrl+A and then press Ctrl+C.
10. Click the Query-Bios.ps1 tab, place the cursor on line 1 and press Ctrl+V.
11. Click the File menu and click Save.
12. To change the current directory, at the Windows PowerShell prompt, type the following command,
and then press Enter:
Set-Location E:\Mod09\Democode
13. To view basic help information, at the Windows PowerShell prompt, type the following command,
and then press Enter:
Get-Help .\Query-Bios.ps1
14. To see the examples in the Windows PowerShell help, at the Windows PowerShell prompt, type the
following command, and then press Enter:
15. To view all of the help information, at the Windows PowerShell prompt, type the following command,
and then press Enter:
16. Close the Windows PowerShell ISE window and the Windows PowerShell prompt.
Advanced scripting 9-9
Lesson 3
Troubleshooting and error handling
Contents:
Question and Answers 10
Demonstration: Troubleshooting a script 10
Demonstration: Handling errors 11
9-10 Automating Administration with Windows PowerShell
Answer: Breakpoints allow you to pause script processing and interact with the variables in the
script. You can query variable values or modify them. You can use this information for
troubleshooting.
2. To rename a text file to a script file, at the Windows PowerShell prompt, type the following command,
and then press Enter:
5. In the Open window, in the address bar, type E:\Mod09\Democode and press Enter.
6. Click 10961C_Mod09_Demo05.ps1 and click Open.
7. In Windows PowerShell ISE, review the code.
8. To set the current directory, at the Windows PowerShell prompt, type the following command, and
then press Enter:
Set-Location E:\Mod09\Democode
9. To view the script output, at the Windows PowerShell prompt, type the following command, and then
press Enter:
.\10961C_Mod09_Demo05.ps1
10. To view the error, at the Windows PowerShell prompt, type the following command, and then press
Enter:
$Error[0]
11. To clear the $Error variable, at the Windows PowerShell prompt, type the following command, and
then press Enter:
$Error.Clear()
12. To create a breakpoint, at the Windows PowerShell prompt, type the following command, and then
press Enter:
13. To run the script, at the Windows PowerShell prompt, type the following command, and then press
Enter:
.\10961C_Mod09_Demo05.ps1
Advanced scripting 9-11
14. To view the value $ComputerName, at the Windows PowerShell prompt, type the following
command, and then press Enter:
$ComputerName
15. To test the value $ComputerName, at the Windows PowerShell prompt, type the following
command, and then press Enter:
16. To test the value $ComputerName, at the Windows PowerShell prompt, type the following
command, and then press Enter:
$ComputerName -eq “”
17. To exit the debug prompt, at the Windows PowerShell prompt, type the following command, and
then press Enter:
exit
20. To view all breakpoints, at the Windows PowerShell prompt, type the following command, and then
press Enter:
Get-PSBreakPoint
21. To remove all breakpoints, at the Windows PowerShell prompt, type the following command, and
then press Enter:
Get-PSBreakPoint | Remove-PSBreakPoint
22. To run the script, at the Windows PowerShell prompt, type the following command, and then press
Enter:
.\10961C_Mod09_Demo05.ps1
23. Close Windows PowerShell ISE and the Windows PowerShell prompt.
2. To rename a text file to a script file, at the Windows PowerShell prompt, type the following command,
and then press Enter:
4. In Windows PowerShell ISE, click the File menu and click Open.
5. In the Open window, in the address bar, type E:\Mod09\Democode and press Enter.
7. Review the code in the script and note that Section 1 with no error checking is the current code.
Section 2 with error checking has a block comment around it.
8. Press F5 to run the script. Notice that an error is generated because LON-SVR1 is not available.
9. On line 3, type <#.
14. Press F5 to run the script. Notice that no error is generated because the error handling displays a
message instead.
15. Close Windows PowerShell ISE and the Windows PowerShell prompt.
Advanced scripting 9-13
Lesson 4
Functions and modules
Contents:
Question and Answers 14
Demonstration: Creating a function in a script 14
Demonstration: Creating a module from a function 14
9-14 Automating Administration with Windows PowerShell
Answer: One big benefit of using script modules is that they are automatically available to all
scripts on a computer. If you have placed your modules in a NuGet repository, you can use
Install-Module to retrieve them from the repository and install them.
2. To rename a text file to a script file, at the Windows PowerShell prompt, type the following command,
and then press Enter:
5. In the Open window, in the address bar, type E:\Mod09\Democode and press Enter.
6. Click 10961C_Mod09_Demo07.ps1 and click Open.
7. Review the code.
8. To set the prompt location, at the Windows PowerShell prompt, type the following command, and
then press Enter:
Set-Location E:\Mod09\Democode
9. To view the size of a folder, at the Windows PowerShell prompt, type the following command, and
then press Enter:
10. To view the size of a folder including subfolders, at the Windows PowerShell prompt, type the
following command, and then press Enter:
11. In Windows PowerShell ISE, insert a blank line at line 1, and then type Function Get-FolderSize {.
17. Close Windows PowerShell ISE and the Windows PowerShell prompt.
2. To set the prompt location, at the Windows PowerShell prompt, type the following command, and
then press Enter:
Set-Location E:\Mod09\Democode\
3. To copy and rename a script file, at the Windows PowerShell prompt, type the following command,
and then press Enter:
5. In Windows PowerShell ISE, click the File menu and click Open.
6. In the Open window, in the address bar, type E:\Mod09\Democode and press Enter.
13. To copy the .psm1 file, at the Windows PowerShell prompt, type the following command, and then
press Enter:
14. To verify that the module is recognized, at the Windows PowerShell prompt, type the following
command, and then press Enter:
Get-Module -ListAvailable F*
15. To verify that the module is not loaded, at the Windows PowerShell prompt, type the following
command, and then press Enter:
Get-Module
16. To use the function in the module, at the Windows PowerShell prompt, type the following command,
and then press Enter:
17. To verify that the module is loaded, at the Windows PowerShell prompt, type the following
command, and then press Enter:
Get-Module
Answer: Yes, you can store a set of credentials to disk by using Export-Clixml. The results on
disk are encrypted and can only be decrypted by the user who originally encrypted them. This
means that storing credentials is useful for single users, but is not useful for scripts that are
shared among multiple users.
Question: Is it possible to use Try..Catch and provide different responses for different errors?
Answer: Yes, it is possible. A single Try statement can have multiple Catch statements associated
with it. You can provide a specific error type to make a Catch statement specific to that error.
Advanced scripting 9-17
Answer: In general, Common Information Model (CIM) is preferred over Windows Management
Instrumentation (WIM) because Microsoft has deprecated WMI. However, in this case, there was
also a requirement to use WS-MAN. Get-CimInstance uses WS-MAN. Get-WmiObject uses
DCOM.
Answer: A friendly error message needs to contain enough information to be useful. In this lab,
indicating that there was an error writing to file is useful, but if you include the path of the file it
is even more useful. Users can review the path to verify whether it is what they expected.
Module 10
Administering remote computers
Contents:
Lesson 1: Using basic Windows PowerShell remoting 2
Lesson 1
Using basic Windows PowerShell remoting
Contents:
Question and Answers 3
Demonstration: Enabling and using remoting 3
Administering remote computers 10-3
Answer: Remoting does require that credentials be delegated across the network, and remoting
offers expanded reach and capability for administrators. Both capabilities can cause security
concerns for some organizations. However, remoting offers several features that enable
organizations to help secure, monitor, and audit it. Remoting does not give administrators
additional permissions. Instead, it gives them a more efficient way to exercise the permissions
that they already have.
Set-ExecutionPolicy RemoteSigned
Enable-PSRemoting
If you receive an error about a network connection being Public, point out the error to students, and
explain that this is a common error. Then run the following command:
Enable-PSRemoting -SkipNetworkProfileCheck
Get-Process
Exit-PSSession
Leave the Windows PowerShell command window open for the next demonstration.
10-4 Automating Administration with Windows PowerShell
Lesson 2
Using advanced Windows PowerShell remoting
techniques
Contents:
Question and Answers 5
Demonstration: Sending local variables to a remote computer 5
Administering remote computers 10-5
Answer: In most cases, you would not do so. The best reason to configure remoting to use
different ports is when your organization uses an application that has to use the same ports.
When you are prompted for a number of log entries that you want to view, enter any desired value
(for example, 5), and then press Enter.
2. Type the following command, and then press Enter:
Point out to students how you can view the number of entries you specified for the Security log.
3. Now try the Using: scope modifier. Type the following command, and then press Enter:
Point out to students that you still view the number of entries you specified for the Security log, just
as you did with -ArgumentList parameter, but the $Using: scope modifier is easier to process.
Leave the Windows PowerShell command window open for the next demonstration.
10-6 Automating Administration with Windows PowerShell
Lesson 3
Using PSSessions
Contents:
Question and Answers 7
Demonstration: Using PSSessions 7
Demonstration: Disconnected sessions 8
Demonstration: Implicit remoting 8
Administering remote computers 10-7
Answer: Because PSSessions are persistent, one concern is that lots of administrators might open
many PSSessions to a single server. That could potentially create a large amount of processing
and memory overhead on the server. You can lessen this concern by:
• Configuring remoting options appropriately to limit the number of PSSessions one
administrator can create.
• Limiting the total number of administrators who may create concurrent PSSessions on a
server.
• The default quota limit should be sufficient in most cases. In the WSMan properties,
MaxShellsPerUser is set to 5 by default.
2. In the Windows PowerShell command window, type the following command, and then press Enter:
Get-PSSession
$dc
Get-Process
Exit-PSSession
$dc
10-8 Automating Administration with Windows PowerShell
$dc | Remove-PSSession
Get-PSSession
Get-PSSession | Remove-PSSession
14. Leave the Windows PowerShell command window open for the next demonstration.
2. To disconnect from the PSSession created above, type the following command, and then press Enter:
3. To open the disconnected PSSession, type the following command, and then press Enter:
4. To reconnect to the PSSession, type the following command, and then press Enter:
5. To confirm that the PSSession is available, type the following command, and then press Enter:
$dc
6. To close the PSSession, type the following command, and then press Enter:
7. Leave the Windows PowerShell command window open for the next demonstration.
Help Get-RemADUser
Note: Be aware that the server may not have updated Help, so the Help you retrieve may
be truncated and include only the Syntax section.
5. To see a list of all domain users, type the following command, and then press Enter:
Get-RemADUser –Filter *
6. To close the session, type the following command, and then press Enter:
$dc | Remove-PSSession
Get-RemADUser
Explain to students that the command will use implicit remoting to re-create a PSSession, and will
prompt you for input to be able to run the command successfully. Explain that if you run Get-
PSSession after this command, you will see that a new session with LON-DC1 has been re-created.
10-10 Automating Administration with Windows PowerShell
There is also concern over the CredSSP protocol that Microsoft describes as an increased security risk. This
is because it enables the delegation of credentials to remote computers, and if those computers are
compromised then the credential could also be compromised. Only trusted, managed, secured computers
should be enabled for CredSSP delegation and even so, the risk is still present. You should use constrained
delegation instead of CredSSP.
Remoting will not enable on a client This frequently occurs because of a network
computer. connection being set to Public, and specifically
when the client has workstation-class virtualization
software installed (which can create many virtual
network adapters). Consider running Enable-
PSRemoting –SkipNetworkProfileCheck to enable
remoting.
Administering remote computers 10-11
Answer: You receive an error that you cannot use the Enter-PSSession cmdlet to enter another
PSSession. By default, you cannot establish a connection through an already-established
connection.
Another benefit is that administrators can more centrally monitor and control access to tools. By
keeping Windows PowerShell commands on a smaller number of computers, you also can easily
update the commands as needed.
Using background jobs and scheduled jobs 11-1
Module 11
Using background jobs and scheduled jobs
Contents:
Lesson 1: Using background jobs 2
Lesson 1
Using background jobs
Contents:
Question and Answers 3
Resources 3
Demonstration: Using background jobs 3
Using background jobs and scheduled jobs 11-3
Answer: Any long-running task is an appropriate candidate for running in the background. Also,
remember that background jobs can run in parallel. That makes background jobs a good way for
a script to start several tasks that can run concurrently. The script can start the jobs and wait until
they all complete before proceeding.
Resources
Enable-PSRemoting
Get-Job
Get-Job
Repeat this step until the RemoteLogs job shows a status of Completed.
11-4 Automating Administration with Windows PowerShell
Replacing <id> with the job ID number you noted from the previous step.
Leave the Windows PowerShell ISE open for the next demonstration.
Using background jobs and scheduled jobs 11-5
Lesson 2
Using scheduled jobs
Contents:
Question and Answers 6
Resources 6
Demonstration: Using a Windows PowerShell script as a scheduled task 6
Demonstration: Using scheduled jobs 7
11-6 Automating Administration with Windows PowerShell
Answer: The ScheduledTasks module is not designed to retrieve job results. It is designed to
manage the task objects in the Windows Task Scheduler. The commands in PSScheduledJob
manage a type of job that combines the abilities of the Windows Task Scheduler with Windows
PowerShell manageability.
Resources
Running Windows PowerShell scripts as scheduled tasks
Reference Links: The Microsoft Script Repository is in the Microsoft Script Center, at
https://aka.ms/il71no.
3. In the details pane of Managers, select one of the user accounts. Right-click the account, and then
select Disable Account, and then click OK in the popup window. Minimize Active Directory Users
and Computers.
4. Click Start, type Task Scheduler, and then select Task Scheduler from the content menu.
5. In the Task Scheduler, in the console tree, right-click Task Scheduler (local) and select Create task.
6. In the Create Task window, in the General tab, in the Name and Description text boxes, type
Delete Disabled User from Managers Security Group. In the Security options, select the Run
whether user is logged on or not, and then select the Run with highest privileges check box.
7. On the Triggers tab, click the New button, and in the New Trigger window, under Settings, select
Daily. In the Start time text box, change the time to 5 minutes from the current time, and then click
OK.
8. On the Action tab, click the New button. In the New Action window, in the Program/script text
box, type PowerShell.exe
10. On the Conditions tab, review the items, but make no changes.
11. In the Settings tab, at the bottom of the window, under If the task is already running, then the
following rule applies: click the drop-down list and select Stop the existing instance. Then click
OK.
12. In the Task Scheduler credentials pop-up, in the Password text box, type Pa55w.rd, and then click
OK.
Using background jobs and scheduled jobs 11-7
13. In the Task Scheduler, click Task Scheduler Library and then in the upper details pane, select the
Delete Disabled User from Managers Security Group item, and then in the lower details pane,
select the History tab. After the five minutes are up, click Refresh in the Actions pane. You should
see an item with Task Category of Task completed.
14. Maximize Active Directory Users and Computers. Double-click the user you disabled. Select the
Member of tab. The user should no longer be a member of the Managers security group.
Get-Job | Remove-Job
You might see an error here stating that the directory name C:\Users\.....\PowerShell\ScheduledJobs is
invalid. This will appear if there are no defined scheduled jobs, and is expected. You run the Remove-
Job command here to clear the jobs before proceeding with the next steps.
2. Type the following command, and then press Enter:
Get-ScheduledJob
Get-Job
Answer: A background job runs only while Windows PowerShell is running. A scheduled job can
run even if Windows PowerShell is not running, and you can still use it to retrieve job results.
The ScheduledTasks module is not This module is a feature of Windows 8 and Windows
available. Server 2012 and newer, and is not available on earlier
versions of the operating system. The
PSScheduledJob module is a feature of Windows
PowerShell 3.0 and newer, and it should be available
on any computer where that version of the shell is
installed.
Using background jobs and scheduled jobs 11-9
Module 12
Using advanced Windows PowerShell techniques
Contents:
Lesson 1: Creating profile scripts 2
Lesson 1
Creating profile scripts
Contents:
Question and Answers 3
Demonstration: Creating a profile script 3
Using advanced Windows PowerShell techniques 12-3
Answer: The location in which you store a user profile script determines whether Windows
PowerShell uses it for all users or just the current user. If the profile script is stored in $pshome,
then Windows PowerShell uses it for all users. If the profile script is stored in
$home\Documents\WindowsPowerShell, then Windows PowerShell uses it only for the
current user.
2. In File Explorer, in the navigation pane, under Quick Access, click Documents.
3. Click the Home tab, click New Folder, type WindowsPowerShell, and then press Enter.
4. Double-click WindowsPowerShell.
5. Click the Home tab, click New Item, and then click Text Document.
6. Clear the existing name, type Profile.ps1, and then press Enter.
13. To display the value of $servers, at the Windows PowerShell prompt, type the following command,
and then press Enter:
$servers
Lesson 2
Using advanced techniques
Contents:
Question and Answers 5
Resources 5
Demonstration: Using regular expressions 5
Demonstration: Using the format operator 7
Demonstration: Setting NTFS permissions 8
Using advanced Windows PowerShell techniques 12-5
Answer: Sometimes external commands use characters that Windows PowerShell tries to
interpret differently. To avoid this, when running an external command, use the stop parsing
symbol (--%) before the arguments.
Resources
Additional Reading: For additional information about the stop parsing symbol, refer to
“About Parsing” at https://aka.ms/vhxi7r.
3. To see that a dot matches one character, type the following command, and then press Enter:
4. To see that a dot does not match zero characters, type the following command, and then press Enter:
5. To see that a question mark matches one character, type the following command, and then press
Enter:
6. To see that a question mark matches zero characters, type the following command, and then press
Enter:
7. To see that a plus matches one instance of the preceding character, type the following command, and
then press Enter:
8. To see that a plus matches multiple instances of the preceding character, type the following
command, and then press Enter:
9. To see that a plus does not match zero instances of the preceding character, type the following
command, and then press Enter:
10. To see that an asterisk matches one instance of the preceding character, type the following
command, and then press Enter:
11. To see that an asterisk matches multiple instances of the preceding character, type the following
command, and then press Enter:
12. To see that an asterisk matches zero instances of the preceding character, type the following
command, and then press Enter:
13. To see that “\w” matches word characters, type the following command, and then press Enter:
14. To see that “\s” matches space characters and not digits, type the following command, and then press
Enter:
15. To see that “\d” matches digit characters, type the following command, and then press Enter:
16. To see matching minimum and maximum instances of a character, type the following command, and
then press Enter:
17. To see matching minimum and maximum instances of a character, type the following command, and
then press Enter:
18. To see matching minimum and maximum instances of a character fail, type the following command,
and then press Enter:
19. To see matching of a substring without defining start and end, type the following command, and
then press Enter:
20. To see matching of a string with the start and end defined fail, type the following command, and
then press Enter:
3. To see index numbers for the format operator, type the following command, and then press Enter:
4. To see alignment, type the following command, and then press Enter:
5. To see the fixed-point format string, type the following command, and then press Enter:
6. To see the number format string, type the following command, and then press Enter:
7. To see the currency format string, type the following command, and then press Enter:
8. To see a custom time format, type the following command, and then press Enter:
"{0,2:hh}:{0,2:mm}" -f (Get-Date)
2. To create a new folder, type the following command, and then press Enter:
3. To put the ACL for the folder in $acl, type the following command, and then press Enter:
4. To view the contents of $acl, type the following command, and then press Enter:
$acl
5. To view a summary of access rules, type the following command, and then press Enter:
$acl.AccessToString
6. To view detailed access rules, type the following command, and then press Enter:
$acl.Access
7. To view the properties and methods for an ACL, type the following command, and then press Enter:
$acl | Get-Member
8. To disable inheritance and clear inherited permissions, type the following command, and then press
Enter:
$acl.SetAccessRuleProtection($true,$false)
9. To create a new access rule for Administrators, type the following command, and then press Enter:
$rule = New-Object
System.Security.AccessControl.FileSystemAccessRule(“Administrators”,”FullControl”,
“ContainerInherit, ObjectInherit”, “None”, “Allow”)
10. To add the access rule to the ACL, type the following command, and then press Enter:
$acl.AddAccessRule($rule)
11. To apply the ACL to C:\Test, type the following command, and then press Enter:
12. To verify that the permissions were modified, type the following command, and then press Enter:
Get-Acl C:\Test | FL
Answer: To specify the number of decimal places for a number or fixed-point format string, you
include an integer that specifies the number of decimal places. For example, n3 is a number with
three decimal places.
Question: Your organization has decided to log all use of Windows PowerShell on domain controllers.
How will you do this?
Answer: You should enable module logging for all modules on the domain controllers by using a
GPO. Module logging captures all Windows PowerShell commands that run and stores them in
the Windows PowerShell operational event log.
12-10 Automating Administration with Windows PowerShell
Answer: Yes, you could have used the Get-ADDomain cmdlet to get the current domain. The
name of the domain is stored in the DistinguishedName attribute.
Question: When you use the format operator to align columns, how do you know how wide to make the
columns?
Answer: You need to select the column width based on the data you expect to display. If you
think that the data will only be five characters, then you can make the column just a little wider
than that.