10961A ENU TrainerHandbook
10961A ENU TrainerHandbook
10961A ENU TrainerHandbook
10961A
Automating Administration
with Windows PowerShell®
MCT USE ONLY. STUDENT USE PROHIBITED
ii 10961A: 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: 05/2013
MCT USE ONLY. STUDENT USE PROHIBITED
MICROSOFT LICENSE TERMS FOR A VIRTUAL ENVIRONMENT THAT INCLUDES THE
FOLLOWING MICROSOFT SOFTWARE:
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 individual Microsoft software titles
named above and any documentation, content, classroom setup guide, supporting and configuration files,
online services, and sample applications provided as part of the virtual environment (all collectively referred
to as the “Virtual Environment”) which includes the media on which you received it, if any. The terms
also apply to any updates, supplements, internet-based services and support services for the Virtual
Environment components.
The virtual hard disk images of the Microsoft software for the Virtual Environment may be provided to you
on one or more virtual hard disks. The individual software titles listed above are ordinarily licensed
separately but are being provided to you under these consolidated license terms for your convenience.
BY ACCESSING ANY PART OF THE VIRTUAL ENVIRONMENT, YOU ACCEPT THESE TERMS. IF
YOU DO NOT ACCEPT THEM, DO NOT ACCESS OR USE ANY VIRTUAL ENVIRONMENT
COMPONENT.
1. DEFINITIONS.
1.1. “Authorized Learning Center” means a Learning Partner, Microsoft IT Academy Program
Member or such other entity as Microsoft may designate in writing.
1.2. “Authorized Training Session” means the Microsoft-authorized instructor-led training class
teaching a Microsoft Course that is conducted by a MCT for an Authorized Learning Center at its
training facility.
1.3. “Classroom Device” means a dedicated personal computer owned or controlled by the Authorized
Learning Center that is located at Authorized Learning Center’s training facility where the
Authorized Training Session is being held that meets or exceeds the hardware level specified for
the particular Microsoft Course title.
1.4. “End User” means an individual duly enrolled in and attending an Authorized Training Session.
1.5. “Learning Partner” means an active member of the Microsoft Partner Network program in good
standing that currently holds and maintains the Learning Competency.
1.6. “MCT” or “Microsoft Certified Trainer” means an individual who is (i) engaged by an Authorized
Learning Center to teach its Authorized Training Session; (ii) currently certified as a Microsoft
Certified Trainer under the Microsoft Certification Program in good standing, and (iii) currently
holds a Microsoft Certification in the technology that is the subject of the Authorized Training
Session.
1.7. “Microsoft Course” means the student-kit version of the Microsoft-branded instructor-led training
course that is licensed from Microsoft that educates individuals on Microsoft technologies. A
MCT USE ONLY. STUDENT USE PROHIBITED
Microsoft Course title may be branded as Microsoft Official Course, Microsoft Dynamics or Microsoft
business group courseware.
1.8. “Microsoft IT Academy Program Member” means an academic institution who is an active
member of the Microsoft IT Academy program.
1.9. “you” means the Learning Partner or a MCT exercising rights under this license.
a. If you are a Learning Partner for each Authorized Training Session you are providing, you may:
i. download and install only those Virtual Environment components listed in the classroom setup
guide for the Microsoft Course title that is the subject of your Authorized Training Session onto
one (1) host Classroom Device running a validly licensed copy of Microsoft Hyper-V to create
the Virtual Environment associated with the Microsoft Course;
ii. either
1. install the Virtual Environment on (1) internal server located at your Authorized Learning
Center training facilities where the Authorized Training Session is being held, OR
2. duplicate the Virtual Environment and install one (1) instance of the Virtual Environment
on one (1) of your Classroom Devices running a validly licensed copy of Microsoft Hyper-
V provided you don’t install the Virtual Environment on more Classroom Devices than the
number of End Users enrolled in that particular Authorized Training Session; and
iii. allow access and use of the Virtual Environment solely via a Classroom Device and only by:
1. one (1) End User who has purchased a valid license for the Microsoft Course title associated
with the Virtual Environment solely to perform the hands-on activities for the Microsoft
Course and only while participating in your Authorized Training Session, and
2. a MCT to prepare for and teach your Authorized Training Session.
b. If you are a MCT for each Authorized Training Session you are teaching, you may:
i. download and install only those Virtual Environment components listed in the classroom setup
guide for the Microsoft Course title that is the subject of the Authorized Training Session onto
one (1) host Classroom Device running a validly licensed copy of Microsoft Hyper-V to create
the Virtual Environment associated with the Microsoft Course;
ii. either
1. install the Virtual Environment components on (1) internal server located at the Authorized
Learning Center training facilities where the Authorized Training Session is being held, OR
2. duplicate and install one (1) instance of the Virtual Environment components on the
Classroom Devices running a validly licensed copy of Microsoft Hyper-V provided you don’t
install the Virtual Environment on more Classroom Devices than the number of End Users
enrolled in that particular Authorized Training Session; and
MCT USE ONLY. STUDENT USE PROHIBITED
iii. duplicate and install one (1) instance of the Virtual Environment on one (1) personal computer
owned by you that is running a validly licensed copy of Microsoft Hyper-V solely for you to
prepare to teach the Authorized Training Session; and
iv. allow access and use of the Virtual Environment solely via a Classroom Device and only by one
(1) End User who has purchased a valid license for the Microsoft Course title associated with
the Virtual Environment solely to perform the hands-on activities for the Microsoft Course and
only while participating in the Authorized Training Session.
2.3. No Other Rights. The Virtual Environment may not be accessed or used on a stand-alone basis. The
Virtual Environment may only be accessed and used in conjunction with the Authorized Training
Session teaching the Microsoft Course title associated with the Virtual Environment. The Virtual
Environment licensed to you under this license agreement may not be used in a live operating or
production environment. No right to distribute, publicly display or perform the Virtual Environment or
any of its components are granted.
2.4. Separation of Components. The Virtual Environment for a Microsoft Course title may include various
software titles, content and other components that may be provided to you on multiple media or
multiple downloads. The Virtual Environment is provided and licensed to you as a single unit to be
used as permitted in Section 2.2. You may not separate the Virtual Environment components and
install them on different devices or servers.
2.5. No Network Access. You may not install the Virtual Environment on Classroom Devices or servers that
are accessible to other networks unless explicitly authorized by Microsoft as documented and specified
in the associated Microsoft Course’s classroom setup guide.
2.6. Reproduction/Redistribution of the Virtual Hard Disk Images of Microsoft Software in the Virtual
Environment. You acknowledge and agree that
a. the Virtual Environment contains virtual hard disk images of Microsoft software;
b. the Microsoft software provided to you under this agreement are valuable assets to Microsoft
and the unauthorized duplication and distribution of such software would deprive Microsoft of
the revenues Microsoft ordinarily collects for licensing such Microsoft software;
c. Microsoft is providing the Microsoft software to you free of charge solely to assist End Users in
gaining proficiency using Microsoft technologies as outlined in this license agreement;
d. you may not sell, rent, lease, loan, transfer, assign or sublicense any portion of the software;
and
e. you may not sublicense, transfer or assign this license or license agreement to any third party.
2.7. Third-party Software. The Virtual Environment may include third party programs that Microsoft, not
the third party, licenses to you under this agreement, unless stated otherwise in this license agreement
or Exhibit A hereto. Notices, if any, for the third-party program are included for your information only.
2.8. Exceptions and additional terms. The exceptions and additional terms (if any) for the Virtual
Environment components are outlined in Exhibit A attached hereto.
2.9. Online Services. If Microsoft makes any online services available to you as part of the Microsoft Course
(“Online Services”) your use of the Online Services is governed by this section and the non-
conflicting terms of the separate online services agreement presented to you. When using Online
Services during a Microsoft Course, you agree (a) that the Online Services may only be used to perform
the hands-on activities for the Microsoft Course title associated with the Virtual Environment, (b) the
authentication credentials you use (or your End User uses) to access the Online Services will not be
tied to any “live” accounts, (c) you license to Microsoft, its affiliates and all necessary sub-licensees all
rights required to use and process all text, sound, images or files (“Data”) uploaded, processed or
stored using the Online Services, (d) you will not nor allow End Users to enter, upload, process or
store any Data containing personally identifiable information in the Online Services, (e) no End Users’
personal devices will used with or enrolled in the Online Services, (f) Microsoft may delete any Data
MCT USE ONLY. STUDENT USE PROHIBITED
at any time without notice and without liability to you, and (g) Microsoft will not provide any support
services for the Online Services.
3. ADDITIONAL LICENSING REQUIREMENTS AND USE RIGHTS.
3.1 You may only use the Virtual Environment if you comply with the terms and conditions of this license
agreement and the following security requirements:
a. You may access, install and use only those components listed as Virtual Environment
components in the classroom setup guide for the Microsoft Course title that is the subject of
the scheduled Authorized Training Session and you may only use the Virtual Environment to
provide or teach a Authorized Training Session that is teaching the Microsoft Course title
associated with the Virtual Environment.
b. You may only use virtual hard disk images of software accompanying this license agreement
to assemble the Virtual Environment.
c. You must assemble and setup the Virtual Environment in accordance with the classroom setup
guide for the Microsoft Course title that is the subject of your scheduled Authorized Training
Session. You may not include or use any of your or any third-party content or software to the
Virtual Environment, unless explicitly authorized by Microsoft as documented in the relevant
classroom setup guide for the Microsoft Course title.
d. You may not install the Virtual Environment on Classroom Devices or servers that are accessible
to other networks unless explicitly authorized by Microsoft as documented in the relevant
classroom setup guide for the Microsoft Course title.
e. Prior to the start of the Authorized Training Session, you must provide all End Users with a
printed copy of the following statement:
“By accessing and using the virtual environment in any way, you acknowledge and agree that
(a) you may only access and use the virtual environment from this classroom device solely to
perform the hands-on activities for this training session, (b) you may not work around any
technical limitations in the virtual environment, (c) you may not download, reproduce, transmit
or forward any software or any virtual environment component in any form or by any means
without Microsoft prior written permission, (d) you may not enter, upload, process or store any
personally identifiable information in the virtual environment, (e) you may not allow a third
party to use or access this virtual environment, and (f) these terms supersede the terms of
any Microsoft license agreement that you may encounter in any virtual environment component
even if installation of or use of that component requires “acceptance” of a separate license
agreement. By using the virtual environment, you agree to abide by these terms. If
you do not agree to these terms, do not use the virtual environment.
This virtual environment is provided “As Is”. Microsoft makes no warranties, express or
implied.”
f. You may only provide access to and use of the Virtual Environment to End Users who have
agreed to abide by the statement in 3.1.e. above.
g. Prior to the start of each Authorized Training Session, you will provide each End User with its
own valid licensed copy of the Microsoft Course title that is the subject of the Authorized
Training Session.
h. You may not allow others to access, forward, copy or download the Virtual Environment.
i. You will strictly comply with all Microsoft instructions relating to installation, activation, use,
deactivation and security of the Virtual Environment.
j. You may not modify the Virtual Environment or any component thereof, unless explicitly
authorized by Microsoft as documented in the associated classroom setup guide for the
Microsoft Course title.
MCT USE ONLY. STUDENT USE PROHIBITED
k. You must remove all copies of the Virtual Environment from the server, all Classroom Devices
and personal devices at the end of the Authorized Training Session and recreate, reinstall and
launch the Virtual Environment prior to the beginning of the next Authorized Training Session.
3.2 If the Virtual Environment includes operating system software that is deactivated, you will need to
obtain a product key from Microsoft to activate the software before configuring the software for the
Virtual Environment. Specific instructions on how to obtain and activate software using a Microsoft
product key are included in the classroom setup guide for the Microsoft Course title. You are responsible
for the use of product keys assigned to you. You may not share your product keys with third parties
and you may not use product keys assigned to third parties.
Activation associates the use of the software with a specific device. During activation, the software will
send information about the software and the device to Microsoft. This information includes the version,
language and product key of the software, the Internet protocol address of the device, and information
derived from the hardware configuration of the device. BY USING THE SOFTWARE, YOU CONSENT
TO THE TRANSMISSION OF THIS INFORMATION. If properly licensed, you have the right to use
the version of the software installed during the installation process up to the time permitted for
activation. UNLESS THE SOFTWARE IS ACTIVATED, YOU HAVE NO RIGHT TO USE THE
SOFTWARE AFTER THE TIME PERMITTED FOR ACTIVATION. This is to prevent its unlicensed
use. YOU ARE NOT PERMITTED TO BYPASS OR CIRCUMVENT ACTIVATION. If the device is
connected to the Internet, the software may automatically connect to Microsoft for activation. You can
also activate the software manually by Internet or telephone. If you do so, Internet and telephone
service charges may apply. Some changes to your computer components or the software may require
you to reactivate the software. THE SOFTWARE WILL REMIND YOU TO ACTIVATE IT UNTIL
YOU DO.
3.3 If the Virtual Environment includes operating system software that does not require a product key for
use, you are required to verify the state of the operating system after installation of the software in
the Virtual Environment. If the operating system is in “Notification” mode, you must rearm the software
to change the state of the operating system prior to the Authorized Training Session.
4. INTERNET-BASED SERVICES. Microsoft may provide Internet-based services with the software in
the Virtual Environment. Microsoft may change or cancel them at any time. If the Virtual Environment
contains pre-release versions of software, some of its Internet-based services may be turned on by
default. The default setting in these versions of the software do not necessarily reflect how the features
will be configured in the commercially released versions. However, should the software be configured
to transmit over the Internet, the following terms apply:
a. Consent for Internet-Based Services. Some of the software features described as Internet-Based
Services in Exhibit A (if any) may connect to Microsoft or service provider computer systems
over the Internet. In some cases, you will not receive a separate notice when they connect. In
some cases, you may switch off these features or not use them. BY USING THESE FEATURES,
YOU CONSENT TO THE TRANSMISSION OF THIS INFORMATION AND YOU ARE
RESPONSIBLE FOR OBTAINING ALL NECESSARY CONSENT FROM ALL END USERS TO
TRANSMIT THIS INFORMATION TO MICROSOFT. Microsoft does not use the information
to identify or contact you.
b. Computer Information. The software features described as Internet-Based Services in Exhibit A
(if any) use Internet protocols, which send to the appropriate systems, computer information,
such as your Internet protocol address, the type of operating system, browser, name and version
of the software you are using and the language code of the device where you run the software.
Microsoft uses this information to make the Internet-based services available to you.
c. Use of Information. Microsoft may use the information and reports to improve our software and
services. We may also share it with others, such as hardware and software vendors. They may
use the information to improve how their products run with Microsoft software.
MCT USE ONLY. STUDENT USE PROHIBITED
d. Misuse of Internet-based Services. You may not use these services in any way that could harm
them or impair anyone else’s use of them. You may not use the services to try to gain
unauthorized access to any service, data, account or network by any means.
5. SCOPE OF LICENSE. The Virtual Environment is licensed, not sold. This agreement only gives you
some rights to use the Virtual Environment. Microsoft reserves all other rights. Unless applicable law
gives you more rights despite this limitation, you may use the Virtual Environment only as expressly
permitted in this license agreement. In doing so, you must comply with any technical limitations in the
Virtual Environment components that only allow you to use it in certain ways. You may not, nor allow
others to:
a. make or install more copies of the Virtual Environment on Classroom Devices than the number
of End Users participating in the Authorized Training Session;
b. allow more Classroom Devices to access the Virtual Environment on the server than the number
of End Users participating in the Authorized Training Session;
c. allow access to or use of the Virtual Environment to anyone except End Users who have
purchased a valid license to the Microsoft Course title that is the subject of the Authorized
Training Session and only while participating in the Authorized Training Session teaching the
Microsoft Course title associated with the Virtual Environment;
d. transmit, publish, link to, post, publicly display, or forward the Virtual Environment, or
otherwise use the Virtual Environment in an unauthorized or illegal manner;
e. reproduce, use, download, provide access to or distribute the Virtual Environment except as
expressly allowed under this agreement;
f. rent, sell, lease, or lend the Virtual Environment, or reproduce the Virtual Environment to any
server or locations for further reproduction or access except as expressly allowed under this
agreement;
g. access or use any of the Virtual Environment for (i) commercial software hosting services, (ii)
general business purposes, or (iii) any purpose which you have not been expressly authorized
by Microsoft under this agreement;
h. add content or software to, alter, modify, adapt, edit, or otherwise create derivative works
based on the Virtual Environment;
i. use the Virtual Environment within another operating system or application running on another
operating system;
j. work around any technical limitations in the Virtual Environment; or
k. reverse engineer, decompile, customize or disassemble Virtual Environment in any way.
Rights to access the Virtual Environment on any device do not give you any right to implement
Microsoft patents or other Microsoft intellectual property in the Virtual Environment and devices
that access that Virtual Environment.
6. RESERVATION OF RIGHTS AND OWNERSHIP. Microsoft and its suppliers reserve all title,
copyright and intellectual property rights in the Virtual Environment and its components.
7. TIME-SENSITIVE SOFTWARE. After initial launch, some of the software in the Virtual Environment
may stop running on the date indicated for the applicable software in the classroom setup guide for
the Microsoft Course. You will not receive any other notice. You may be able to use the re-arm
command to reset the software in the Virtual Environment to run it for an additional period of time.
The number of days the software will run per launch and the number of times you may run the re-arm
command varies as indicated in the Microsoft Course’s classroom setup guide.
You must stop all access to and use of the Virtual Environment if any software in the Virtual
Environment stops running and you have exhausted all re-arms (if available). You will not be able to
access, use or retrieve data from the Virtual Environment once the software stops running.
MCT USE ONLY. STUDENT USE PROHIBITED
8. TERM AND TERMINATION. This agreement will automatically and immediately terminate upon the
earliest of (a) the earliest software expiration date as indicated in Exhibit A (if applicable) and/or the
classroom setup guide and all re-arms have been exhausted (if available); (b) termination of this
agreement by Microsoft; (c) (i) upon expiration or termination of your Learning Competency status
under the Microsoft Partner Network program if you are a Learning Partner, or (ii) upon termination or
expiration of your status as a MCT if you are a MCT; or (d) conclusion of the earliest beta term for any
pre-release software included in the Virtual Environment (if applicable).
Microsoft may immediately terminate this agreement if it has reason to believe you failed to comply
with any of the terms and conditions in this agreement.
Upon termination of this agreement for any reason, all rights granted to you under this agreement will
immediately terminate and you must immediately stop all access to and use of the Virtual Environment
and permanently delete and destroy all copies of the Virtual Environment in your possession and under
your control.
9. FEEDBACK. If you give feedback about the Virtual Environment to Microsoft, you give to Microsoft,
without charge, the right to use, share and commercialize your feedback in any way and for any
purpose. You also give to third parties, without charge, any patent rights needed for their products,
technologies and services to use or interface with any specific parts of a Microsoft software or service
that includes the feedback. You will not give feedback that is subject to a license that requires Microsoft
to license its software, products, technologies, services or documentation to third parties because we
include your feedback in them. These rights survive this agreement.
10. EXPORT RESTRICTIONS. The software in the Virtual Environment 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 software. These laws include restrictions on destinations, end users and end use. For
additional information, see www.microsoft.com/exporting.
11. SUPPORT SERVICES. Because this Virtual Environment is provided “as is,” Microsoft may not provide
support services for it.
12. ENTIRE AGREEMENT. This agreement, and the terms for supplements, updates, Internet-based
services, Online Services (if applicable) and support services that you use are the entire agreement for
the Virtual Environment and support services.
13. APPLICABLE LAW.
a. United States. If you acquired the Virtual Environment components in the United States,
Washington state law governs the interpretation of this agreement and applies to claims for
breach of it, regardless of conflict of laws principles. The laws of the state where you live govern
all other claims, including claims under state consumer protection laws, unfair competition laws,
and in tort.
b. Outside the United States. If you acquired the Virtual Environment components in any other
country, the laws of that country apply.
14. LEGAL EFFECT. This agreement describes certain legal rights. You may have other rights under the
laws of your country. 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.
15. DISCLAIMER OF WARRANTY. THE VIRTUAL ENVIRONMENT, EACH OF ITS COMPONENTS
AND ONLINE SERVICES ARE LICENSED “AS-IS.” YOU BEAR THE RISK OF USING IT.
MICROSOFT 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 EXCLUDES THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR
A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
MCT USE ONLY. STUDENT USE PROHIBITED
16. LIMITATION ON AND EXCLUSION OF REMEDIES AND DAMAGES. YOU CAN RECOVER FROM
MICROSOFT AND ITS SUPPLIERS ONLY DIRECT DAMAGES LIMITED TO THE GREATER OF
THE AMOUNT ACTUALLY PAID FOR THE VIRTUAL ENVIRONMENT OR U.S. $5.00. YOU
CANNOT RECOVER ANY OTHER DAMAGES, INCLUDING CONSEQUENTIAL, LOST PROFITS,
SPECIAL, INDIRECT OR INCIDENTAL DAMAGES.
This limitation applies to
a. anything related to the Virtual Environment, its components, Online Services and content
(including code) on third party internet sites, or third party programs; and
b. claims for breach of contract, breach of warranty, guarantee or condition, strict liability,
negligence, or other tort to the extent permitted by applicable law.
It also applies even if Microsoft knew or should have known about the possibility of the damages. The
above limitation or exclusion may not apply to you because your country may not allow the exclusion
or limitation of incidental, consequential or other damages.
v.4.13
MCT USE ONLY. STUDENT USE PROHIBITED
EXHIBIT A
The license terms set forth in the agreement and the following exceptions and additional terms shall apply
to the following Microsoft components included in the Virtual Environment:
Exceptions and Additional Terms for Remote Server Administration Tools for Windows 8. Remote Server
Administration Tools for Windows 8 can be installed ONLY on computers that are running Windows 8.
Remote Server Administration Tools cannot be installed on computers with an Advanced RISC Machine
architecture or other system-on-chip devices.
MCT USE ONLY. STUDENT USE PROHIBITED
MCT USE ONLY. STUDENT USE PROHIBITED
10961A: Automating Administration with Windows PowerShell® xiii
MCT USE ONLY. STUDENT USE PROHIBITED
xiv 10961A: Automating Administration with Windows PowerShell®
Acknowledgments
Microsoft Learning would like to acknowledge and thank the following for their contribution towards
developing this title. Their effort at various stages in the development has ensured that you have a good
classroom experience.
Contents
Module 1: Getting Started with Windows PowerShell
Lesson 1: Overview and Background 1-2
Lab A: Configuring Windows PowerShell 1-9
Lesson 2: Finding and Learning Commands 1-11
Lesson 3: Running Commands 1-19
Lab B: Finding and Running Basic Commands 1-25
Course Description
This five day course is designed to teach IT professionals the core skills needed to use Windows
PowerShell 3.0 to automate administrative tasks. The course uses Microsoft Windows 8 and Microsoft
Windows Server 2012 for examples and labs, but the skills taught in this course are applicable to Microsoft
Exchange Server 2010 and later, Microsoft SharePoint Server 2010 and later, Microsoft SQL Server 2008 R2
and later, Microsoft Windows Server 2008 R2, Microsoft Windows 7, and other products that use Windows
PowerShell. This course does not focus primarily on scripting or programming, although it does include
lessons that feature basic scripting tasks. The course focuses mainly on using Windows PowerShell as an
interactive command line interface. Major Windows PowerShell feature coverage includes remoting,
background jobs, scheduled jobs, the pipeline, Windows Management Instrumentation (WMI) and
Common Information Model (CIM), output formatting, output conversion, and exporting.
Audience
This course is intended for students who want to use Windows PowerShell to automate administrative
tasks from the command line, using any Microsoft or independent software vendor (ISV) product that
supports Windows PowerShell manageability. This course is not intended to be a scripting or
programming course, and includes only basic coverage of scripting and programming topics. Students are
not expected to have prior scripting or programming experience, and are not expected to have prior
Windows PowerShell experience.
Student Prerequisites
This course requires that you have the ability to meet following prerequisites:
• Previous Windows Server and Windows Client management knowledge and hands on experience.
• Experience Installing and Configuring Windows Server into existing enterprise environments, or as
standalone installations.
• Knowledge and experience of network adapter configuration, basic Active Directory user
administration, and basic disk configuration.
• Knowledge and hands on experience specifically with Windows Server 2012 and Windows 8 would be
of benefit but is not essential.
• Students who have prior experience in a scripting or programming language may have an easier time
with some of this course’s advanced concepts but previous scripting or programming experience is
not required.
Course Objectives
After completing this course, students will be able to:
Course Outline
The course outline is as follows:
This module introduces students to Windows PowerShell, explains the two built-in host applications, and
teaches students to configure the host applications.
This module explains how Windows PowerShell passes objects from command to common within the
pipeline. Students are given several examples and learn to explain the pipeline operation and predict
command behavior.
This module explains the purpose and use of Windows PowerShell providers and drives, and shows
students how to use these components for administrative tasks.
This module demonstrates how to format command output and how to create custom output elements.
This module explains Windows Management Instrumentation (WMI) and Common Information Model
(CIM), and shows students how to use these technologies.
This module prepares students for scripting by explaining Windows PowerShell’s security model and
formally covering variables.
This module shows students how to take a command and turn it into a parameterized script, and how to
evolve that script into a standalone script module. Students therefore learn the foundations needed to
create their own reusable tools.
This module explains Windows PowerShell remoting, and shows students how to use remoting to manage
multiple remote computers.
This module offers students an opportunity to use everything they have learned so far. Students will
discover, learn, and run commands that perform a complex, real-world administrative task.
In this module students will learn to create and manage background jobs and scheduled jobs.
Exam/Course Mapping
This course, 10961A: Automating Administration with Windows PowerShell, does not have a direct
mapping to any exam.
However, while there is not a standalone Windows PowerShell exam it is covered across all the individual
Microsoft Certified Solutions Associate (MCSA) and Microsoft Certified Certified Solutions Expert (MCSE)
exams and this course will help prepare you for Windows PowerShell related concepts and processes
within those exams.
Course Materials
The following materials are included with your kit:
• Course Handbook A succinct classroom learning guide that provides all the critical technical
information in a crisp, tightly-focused format, which is just right for an effective in-class learning
experience.
• Lessons: Guide you through the learning objectives and provide the key points that are critical to
the success of the in-class learning experience.
• Labs: Provide a real-world, hands-on platform for you to apply the knowledge and skills learned
in the module.
• Module Reviews and Takeaways: Provide improved on-the-job reference material to boost
knowledge and skills retention.
• Lab Answer Keys: Provide step-by-step lab solution guidance at your fingertips when it’s
needed.
MCT USE ONLY. STUDENT USE PROHIBITED
xx About This Course
• Modules: Include companion content, such as questions and answers, detailed demo steps and
additional reading links, for each lesson. Additionally, they include Lab Review questions and
answers and Module Reviews and Takeaways sections, which contain the review questions and
answers, best practices, common issues and troubleshooting tips with answers, and real-world
issues and scenarios with answers.
• Resources: Include well-categorized additional resources that give you immediate access to the
most up-to-date premium content on TechNet, MSDN®, and Microsoft Press®.
• Course evaluation At the end of the course, you will have the opportunity to complete an online
evaluation to provide feedback on the course, training facility, and instructor.
Important At the end of each lab, you must close the virtual machine and must not save
any changes. To close a virtual machine without saving the changes, perform the following
steps:
1. On the virtual machine, on the Action menu, click Close.
2. In the Close dialog box, in the What do you want the virtual machine to do? list, click
Turn off and delete changes, and then click OK.
The following table shows the role of each virtual machine that is used in this course.
Software Configuration
The following software is installed on each virtual machine:
Course Files
There are lab files associated with the labs in this course. The lab files are located in the folder
E:\Allfiles\Labfiles\LabXX on LON-CL1.
Classroom Setup
Each classroom computer will have the same virtual machines configured in the same way.
Module01
Getting Started with Windows PowerShell
Contents:
Module Overview 01-1
Module Overview
Even if you are familiar with command-line interfaces from other operating systems, or if you have used
the Cmd.exe shell in Windows, you must learn (and in some cases, re-learn) important concepts and
techniques before you can start to be effective with Windows PowerShell.
This module will introduce you to Windows PowerShell and provide an overview of the product’s
functionality. You will learn to open and configure the shell for use and how to run commands within the
shell. You will also learn about Windows PowerShell’s built-in Help system. It plays an important role in
helping you learn how to use the shell’s many commands.
Additional Reading: You may be interested in the Windows PowerShell team blog, located
at http://blogs.msdn.com/powershell.
Additional Reading: If you need community-based help for Windows PowerShell, visit
http://www.PowerShell.org or http://social.technet.microsoft.com/Forums/en/category/scripting.
Objectives
After completing this module, students will be able to:
Lesson 1
Overview and Background
It is easy to overlook the background and intended purpose of Windows PowerShell and to just jump in
and start using it. But understanding where Windows PowerShell comes from, and what it is intended to
do, can help you use it more easily and more effectively.
In this lesson, you will learn about Windows PowerShell’s system requirements and learn to open and
configure the two included host applications.
Lesson Objectives
After completing this lesson, students will be able to:
Windows PowerShell’s main functionality is provided by commands. These come in many varieties:
cmdlets (pronounced “command-lets”), functions, workflows, and more. These commands are building
blocks, designed to be pieced together to implement complex and customized processes and procedures.
Windows PowerShell 3.0 is installed by default on Windows 8 and Windows Server 2012, and is available
as an out-of-band free download for Windows 7 with Service Pack 1 (SP1), Windows Server 2008 (SP2),
and Windows Server 2008 R2 (SP1). Be aware that Windows PowerShell 3.0 is incompatible with Windows
XP, Windows Server 2003, and Windows Vista. The out-of-band free download package in which
Windows PowerShell 3.0 is available is the Windows Management Framework 3.0. As well as Windows
PowerShell v3.0 it also includes Windows Management Instrumentation (WMI), WinRM, Management
Open Data Protocal (OData) Internet Information Services (IIS) Extension, and Server Manager Common
Information Model (CIM) Provider updates. The WinRM feature in Windows PowerShell 3.0 is compatible
with the same feature in Windows PowerShell 2.0. Therefore, the two versions can successfully
communicate with one another for management.
Windows PowerShell 3.0 requires Windows PowerShell 4.0 of the Microsoft® .NET Framework; older
versions of Windows PowerShell required Windows PowerShell 2.0 of the .NET Framework.
Reference Links: The Windows Management Framework 3.0 is available for download here
http://www.microsoft.com/en-us/download/details.aspx?id=34595.
MCT USE ONLY. STUDENT USE PROHIBITED
01-4 Getting Started with Windows PowerShell
The ISE is a Windows Presentation Foundation (WPF) application that provides rich editing capabilities,
IntelliSense code hinting and completion, and support for double-byte character sets. However, it does
not support all Windows PowerShell functionality. Most notably, it cannot capture shell activity to a text
transcript file. The ISE also does not support multiline commands. For example, in the console, you could
type this:
PS C:\> Get-Service |
>> Out-File C:\services.txt
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 01-5
>>
In that example, you press Enter after typing the pipe character (|), and the console allows you to continue
typing the command line on the next physical line. Pressing Enter on a blank line executes everything that
you typed up until that point. The ISE does not support that technique.
In this course, you will begin by using the console. This is a good way to reinforce important foundational
skills. Toward the end of the course, you will shift to using the ISE as you begin to link multiple commands
together into scripts.
Third parties can provide other Windows PowerShell host applications. Several companies produce free
and commercial Windows PowerShell scripting, editing, and console hosts. This course will focus on the
host applications provided with the Windows® operating system.
Note:
The language version used in Windows
PowerShell 1.0 is also used in Windows PowerShell 1.0, Windows PowerShell 2.0, and Windows
PowerShell 3.0. The language version indicates the keywords used for Windows PowerShell
scripts.
To correctly determine the version, type $PSVersionTable in Windows PowerShell and press Return. The
shell will display the version numbers for various components. This includes the main Windows PowerShell
version number. Be aware that this technique will not work in Windows PowerShell 1.0; it will return a
blank result.
When you install Windows PowerShell 3.0 on a system that already has Windows PowerShell 2.0 installed,
Windows PowerShell 3.0 will install side by side, leaving the Windows PowerShell 2.0 engine available for
execution. This behavior is meant to help with potential compatibility issues by providing the Windows
PowerShell 2.0 engine for applications that require it and that are incompatible with the Windows
PowerShell 3.0 engine. Be aware that running Windows PowerShell in 2.0 mode does not provide 100
percent Windows PowerShell 2.0 compatibility, because some commands’ behavior has changed in
Windows PowerShell 3.0. Running in 2.0 mode changes only the version of the Windows PowerShell
engine used to run those commands.
To run the shell in Windows PowerShell 2.0 mode, in the Windows PowerShell console, run the command
PowerShell.exe –version 2.0 and press return. If you then run the $PSVersionTable command, the
command will display a PSVersion value of 2.0.
MCT USE ONLY. STUDENT USE PROHIBITED
01-6 Getting Started with Windows PowerShell
On computers that have User Account Control (UAC) enabled, Windows PowerShell can be opened
without Administrative Credentials. Because you will frequently be using the shell to perform
administrative tasks, you may have to make sure that the shell opens with full Administrative Credentials.
To do this, right-click the application icon and select Run as Administrator from the shortcut menu.
When you are running with Administrative Credentials, the application’s window title bar will say
Administrator. Make sure that you check this when you open the shell.
If any of these characters seem too similar to one another, try configuring the console to use a different
font. TrueType fonts in particular may be easier to read than the default Raster font. To configure a new
font, click the control box in the upper-left corner of the console window. From the shortcut menu, select
Properties, and then select the Font tab. You can also select a font size on this tab.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 01-7
You should also size the shell window to fit completely on your screen so that no command output will be
positioned off-screen. In addition, configure the console window not to have a horizontal scroll bar. To do
this, open the console property dialog box again, and then select the Layout tab. Make sure that both the
Screen Buffer Size and Window Size have the same value that is shown for Width (it is fine for the
Height to be significantly larger for the Screen Buffer Size). Close the dialog box and verify that the
window fits on the screen and that no horizontal scroll bar is shown. A vertical scroll bar will stil be present
in the console.
Finally, if you are dissatisfied with the default white-on-blue color scheme, the console’s Properties dialog
box lets you select from a small range of alternative colors. Use the Colors tab to do this, noting that you
can change only the primary text color. The color of error messages and other output cannot be changed
from this dialog box.
Remember that the console host does support Clipboard copying and pasting, although it does not use
standard keyboard shortcuts. Use the mouse pointer to highlight a block of text, and press Enter to copy
that text to the Clipboard. Right-click the mouse button to paste. For this copy and paste functionality to
work, you need to ensure that QuickEdit Mode is enabled in the console’s Properties dialog box, on the
Options tab that is in the Edit Options section. On some computers, this mode may be enabled by default.
Demonstration Steps
1. Open the 64-bit Windows PowerShell console host as Administrator.
4. Configure the window layout so that the whole window fits on the screen and does not display a
horizontal scroll bar.
5. Start a shell transcript.
Command Pane is also displayed, which enables you to search for commands, browse available
commands, and fill in parameters for a command you select.
The ISE gives you the ability to customize its view in a number of ways. A slider in the lower-right area of
the window changes the active font size, whereas the Options dialog box lets you customize font and
color selection for many different Windows PowerShell text elements, such as keywords, string values, and
more. The ISE supports visual themes. It provides several built-in themes and gives you the option to
create custom themes. A theme is a collection of font and color settings that can be applied as a group to
customize the tool’s appearance.
Other ISE features include a built-in, extensible snippets library; the ability to load functionality add-ins
created by Microsoft or by third parties; integration with Windows PowerShell’s debugging capabilities;
and more.
Demonstration Steps
1. Use the Windows PowerShell taskbar icon to open the Windows PowerShell ISE.
2. Open the ISE by running a command from the Windows PowerShell console application.
3. Use toolbar buttons to arrange the Script Pane and Console pane.
Question: Why might you decide to use the ISE over the console host?
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 01-9
Objectives
After completing this lab, students will be able to:
Lab Setup
Estimated Time: 15 minutes
Virtual Machines: 10961A-LON-DC1, 10961A-LON-CL1
Password: Pa$$w0rd
Be aware that the changes that you make during this lab will be lost if you revert your virtual machines at
another time during class.
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must
complete the following steps:
1. On the host computer, move the pointer over the bottom left corner of the taskbar, click Start, and
then click Hyper-V Manager on the Start screen.
2. In Hyper-V® Manager, click 10961A-LON-DC1, and in the Actions pane, click Start.
3. In the Actions pane, click Connect. Wait until the virtual machine starts.
b. Password: Pa$$w0rd
c. Domain: ADATUM
1. Start the 64-bit console application as Administrator and pin Windows PowerShell icon to the taskbar
Task 1: Start the 64-bit console application as Administrator and pin Windows
PowerShell icon to the taskbar
1. On the 10961A-LON-CL1 virtual machine, log on as Adatum\Administrator.
3. Size the window to fit on the screen and to remove any horizontal scroll bar.
Results: After completing this lab, you will have opened and configured the Windows PowerShell console
application and configured its appearance and layout.
2. Customize the appearance of the ISE to use the single-pane view, hide the Command Pane, and
adjust the font size.
Task 2: Customize the appearance of the ISE to use the single-pane view, hide the
Command Pane, and adjust the font size
1. Configure the ISE to use single-pane view and display the console pane.
Results: After completing this lab, you will have customized the appearance of the Windows PowerShell
ISE application.
Question: Why might you decide to use the console application instead of the ISE?
Question: Why might you configure alternative text colors in the ISE?
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 01-11
Lesson 2
Finding and Learning Commands
In this lesson, you will learn to use Windows PowerShell’s Help system to discover new commands, and to
learn how to use them. You will also learn the correct syntax for running Windows PowerShell commands,
and learn about shortened syntax forms that can be used to lessen how much typing you have to do in
the shell.
Lesson Objectives
After completing this lesson, students will be able to:
Familiar-Seeming Commands
When you first start using Windows PowerShell,
especially for file and folder management, the
commands can seem to be familiar. Dir gives you
a listing of files and folders (as does Ls), Cd
changes folders, and Type (or Cat) displays the
contents of a text file. Run Dir > directory.txt to
redirect a directory listing into a text file, or run
Mkdir to create a new directory. Even commands
like Ping and Ipconfig return familiar-looking
results.
Viewing the Help in the console window (or the console pane of the ISE) can sometimes be less-than-
satisfactory. Try running help dir –ShowWindow to display the Help in a separate, floating window,
which could even be moved to a second monitor. This makes it easier to read the Help while typing your
command.
One of the most common reasons to seek out help is to find usage examples for a command, and
Windows PowerShell typically includes many such examples. For example, run help dir –example to see
examples of using the Get-ChildItem command. These can also be viewed near the end of the Help file
when you are using the –ShowWindow option.
Finally, understand that Help files may occasionally contain errors or omissions. They are, after all, the
product of human beings! Windows PowerShell offers two methods for obtaining the most recent Help
content. First, the updatable Help system is capable of downloading updated Help to your computer, and
you will explore that capability later in this module. Second, you can view online versions of the Help files.
Because these are published online, Microsoft can publish updates with whatever frequency is necessary.
For example, to view the online Help for Get-ChildItem, run help Get-ChildItem –online. Be aware that
this requires an Internet connection and will display Help in your computer’s default web browser.
Demonstration Steps
1. Display basic Help for a command.
Finding Commands
Because Windows PowerShell has extensive built-
in help, you can frequently learn how to use a
command fairly quickly. The inclusion of usage
examples further facilitates new command usage.
The trick frequently is, then, to find the command
in the first place. What command would you use
to set an IP address on a network adapter? What
command displays mailboxes in Exchange Server
2010? What command disables an Active
Directory® user account?
Note: Windows PowerShell uses the generic term command to refer to cmdlets, functions,
workflows, applications, and other items. There are some differences in how these different items
are created, but for now you can consider them to all work in the same way.
First, be aware that much of Windows PowerShell’s functionality comes from add-in modules, each of
which can add more commands to the shell’s capabilities. When it is stored in the correct location (which
you will explore later in this course), Windows PowerShell can detect these modules even when they are
not loaded into memory, and can inventory their available commands. This module discovery feature
enables Help and Get-Command to help you discover any command installed on your computer, even if
the module that contains that command hasn’t yet been loaded into memory. When you run a command
whose module hasn’t yet been loaded into memory, module autoloading will implicitly load the module.
This makes the command available for execution.
The Get-Help command accepts wildcard characters, notably the asterisk (*) wildcard character. When
you ask for help and use wildcard characters with a partial command name, the shell will display a list of
matching Help topics. This helps you find commands by making guesses.
Windows PowerShell’s native commands—that is, those built into the shell and added in through
modules—follow a strict naming convention that consists of a verb (or a verb-like word) and a
singular noun. Listing processes, for example, is performed by running Get-Process. Listing services is
performed by Get-Service. Creating a new service is performed by New-Service. The list of verbs is
managed by Microsoft and can be viewed by running Get-Verb. As soon as you become familiar with
this naming convention, you can start to make good guesses about command names. Do you need to
display a list of mailboxes in Exchange Server? Get-Mailbox might be a good guess, and you could
validate that by running Help *mailbox*.
Note: The Command Pane in the ISE application can also be used to find commands. It lists
all installed commands alphabetically, and lets you type a partial command name to see
matching commands.
When you make a command name guess, try to stick with just the noun portion, and consider just a
single-word, singular noun. For example, event and log might be good guesses when you are trying to
find a command that works with Windows event logs.
MCT USE ONLY. STUDENT USE PROHIBITED
01-14 Getting Started with Windows PowerShell
Get-Command also accepts wildcard characters. This means that you can run Get-Command *event*.
This command also has two parameters that let you specify a specific verb or noun. For example, run Get-
Command –Noun event* or Get-Command –Verb Get to see a list of commands whose nouns start
with event or a list of commands that use the Get verb.
Note: Not all terms identified as verbs are actual English verbs. For example, New is not a
verb, but it is the word Windows PowerShell uses to describe the operation of creating something
new. Windows PowerShell uses the term verb somewhat loosely in this respect.
Sometimes, you may specify a wildcard search that cannot be fulfilled by a command name. For example,
running Help *beep* will not find any commands that have beep in their name. So, the Help system will
conduct a full-text search of available command descriptions and synopses. This would locate any Help
files that contain beep. If only a single file is found with a match, the Help system will display it instead of
showing a one-item list.
You can access a list of all installed modules by running Get-Module –ListAvailable. With the module
names in front of you, you can easily list the commands in each module, and use Help to learn how to use
each command.
Demonstration Steps
1. Find a command that could convert content to HTML.
2. Show a list of commands that can create new items. Notice that Windows PowerShell uses the word
new as a verb, although in English the word is not actually a verb.
3. Find a command that could restart a computer.
5. There is a command able to read Windows Event Logs (actually, there are two). Can it do so from a
remote computer in addition to the local one?
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 01-15
The actual –LogName parameter name is listed in square brackets, meaning it is a positional parameter.
The command cannot be run without a log name. But you do not have to actually type the –LogName
parameter name. You have to pass the log name string in the first position, because that is the position in
the Help file where the –LogName parameter appears. Therefore, the following two commands are
functionally equivalent:
Note: More information about each parameter can be found by viewing the command’s
full help. For example, run Help Get-EventLog –Full to see the full Help for Get-EventLog, and
notice the additional information displayed. You can, for example, confirm that the –LogName
parameter is mandatory and appears in the first position.
Be cautious when omitting parameter names. One reason for caution is that you cannot do so with every
parameter. The –ComputerName parameter, as one example, cannot have the parameter name omitted.
Another reason for caution is that you can quickly lose track of what goes where. When you provide
parameter names, the parameters can come in any order:
However, when you omit a parameter name, you become responsible for getting everything in the correct
order. The following command, for example, will not work because the log name is being passed in the
wrong position:
Best Practice: If you are just getting started with Windows PowerShell, try to provide full
parameter names instead of passing parameter values by position. Full parameter names make
MCT USE ONLY. STUDENT USE PROHIBITED
01-16 Getting Started with Windows PowerShell
commands easier to read and troubleshoot, and they make it easier to see when you are typing
the command incorrectly.
Full Help
Although the brief syntax section of the Help file can be useful as a quick reminder, it does not provide a
high level of detail about each parameter. Reading a command’s full Help provides much deeper detail.
For example, run Get-Help Get-Service –Full and see how much additional information you receive.
• Whether each parameter has a default value (although this information is not consistently
documented across all commands)
• Whether a parameter can accept a value in a specific position (in which case the position number,
starting from 1, is given), or whether you must type the parameter name (in which case named is
shown)
• Whether a parameter accepts pipeline input, and if this is the case, how (which will become important
in the next module)
Full Help also includes extended command descriptions and examples.
Updating Help
Windows PowerShell 3.0 does not ship with Help
files. Instead, Help files are provided as an online
service. Microsoft-authored commands have their
Help files hosted on a Microsoft-owned Web
server; third-party commands can also use
downloadable help, provided the author or
vendor builds the module correctly and provides
an online location for the Help files.
Run Update-Help to scan your computer for all installed modules, retrieve online Help locations from
each, and try to download Help files for each. You must run this command as a member of the local
Administrators group, because Windows PowerShell core command Help is stored in the %systemdir%
folder. Be aware that error messages will be displayed if Help cannot be downloaded for any locally
installed module or modules. When Help cannot be downloaded, Windows PowerShell will still create a
default Help display for the commands in the affected module.
Windows PowerShell defaults to downloading Help files in whatever language your system is configured
to use. If Help is not available in that language, Windows PowerShell defaults to the en-US (US English)
language. You can override this behavior by using a parameter of Update-Help to specify the culture for
which you want to retrieve help.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 01-17
By default, Update-Help will check for Help files only once every 24 hours, even if you run the command
multiple times in a row. To override this behavior, specify the command’s –force parameter.
Note: You should be aware that your lab virtual machines may not be connected to the
Internet and thus may be unable to run Update-Help successfully. For your convenience, the
virtual machines were populated with the latest Help content at the time that they were created.
The companion to Update-Help is Save-Help. It downloads the Help content but saves it to a location
that you specify. That content can then be accessed by, or physically moved to, computers that are not
connected to the Internet. Update-Help offers a parameter to specify an alternative source location. This
enables those disconnected computers to update from that source location.
Remember that both Update-Help and Save-Help will download Help only for modules that are installed
on the computer where the command is run. They will not download Help for modules that are located
on other computers.
"About" Files
Although much of the Help content in Windows
PowerShell is related to commands, there are also
many Help files that describe Windows PowerShell
concepts. These files include information about
the Windows PowerShell scripting language,
operators, and other details. This information is
not specifically related to a single command but
rather relate to global shell techniques and
features.
For much of the rest of this course, you will be referred to these “About” files for additional
documentation. Frequently, you must read these files to discover the steps and techniques needed to
complete lab exercises.
Demonstration Steps
1. View a list of “About” topics.
4. View a Help topic that will explain how to make the console beep.
Question: Is there a way to specify multiple keywords when you search Help?
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 01-19
Lesson 3
Running Commands
Now that you have some familiarity with how to find commands and learn their syntax, you can start to
run commands. Paying extra attention to syntax will help you avoid many of the challenges that Windows
PowerShell newcomers frequently experience.
Lesson Objectives
After completing this lesson, students will be able to:
Following a command are zero or more parameters. In the full syntax, each parameter starts with a dash
or hyphen, followed by the parameter name, a space, and then the parameter’s value:
You should be aware that Windows PowerShell is not case-sensitive in most cases; typing a command
name and its parameter names (and even usually the values) in all-lowercase will not make a difference.
You can use tab completion in both the console and the ISE applications to make typing easier, to avoid
typos, and to double-check the syntax of the command. For example, try the following, pressing the Tab
key every time that you see [tab]:
Command names, parameter names, and even some parameter values can be completed in this manner.
Get-EventLog –Application
Here, the user probably meant to specify –LogName Application but has become confused. Merely
providing Application without the dash would also have worked, because –LogName can accept a value
by position. Here, the user has mixed up the two techniques, and specified a nonexistent parameter -
Application without a value.
These all add spaces where the shell is not expecting them, and the commands will not work.
-ComputerName <string[]>
Another way to specify multiple values is with a parenthetical command. This is a technique you will
explore in more detail later, but generally it works as follows: suppose that you have a text file that lists
one computer name per line:
LON-CL1
LON-DC1
If that file was named C:\computers.txt, you could use it in a parenthetical command as follows:
Note: Get-Content is the command behind the aliases Type and Cat. It reads the content
from the text file and returns each line of the text file as a separate item.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 01-21
A final technique would be to put the content into a variable, and pass the variable to the parameter. You
will learn more about variables in upcoming modules. But an example of the correct syntax looks as
follows:
• Parameter names can be omitted entirely for positional parameters. Instead, pass values in the
appropriate command-line positions.
• All parameter names can be truncated, or shortened. You have to type only enough of each
parameter name for the shell to be able to disambiguate. That is, you have to type enough characters
so that the shell can determine the single parameter that you mean.
The second version is obviously easier to type, but it also somewhat more cryptic and more difficult to
read.
Note: Instead of truncating or omitting parameter names, consider using tab completion
instead. If you have already typed enough of the parameter name for the shell to disambiguate,
you just have to press Tab to complete the name. The complete parameter name will always be
easier to read for someone else who is trying to understand or maintain your commands.
Best Practice: In any form of permanent storage, whether a script file or an Internet blog,
try to use the full command syntax. Use full command names, full parameter names, and names
for all parameters. If you do this, it makes your commands easier for other people to read and
understand.
MCT USE ONLY. STUDENT USE PROHIBITED
01-22 Getting Started with Windows PowerShell
Show-Command
Show-Command is a special Windows PowerShell
command that accepts a single command name
and then displays a graphical dialog box that has
that command’s parameters. Each parameter set is
shown on a separate tab. This makes it visually
clear that parameters cannot be mixed and
matched between sets. To start the dialog box,
specify the command name that you want to see:
Show-Command Get-WinEvent
Note: In these examples, Show-Command is the command that you are actually running,
but Get-WinEvent is the name of the command that you want to see in the dialog box.
As soon as you fill in the desired parameter values, you can run the command immediately or copy it to
the Clipboard. After copied, it can be pasted into the shell so that you can see the correct command-line
syntax without running the command.
The Command Pane in the ISE application provides similar functionality. After you have found the
command that you want in the Command Pane’s list, you click that command to switch to a view very
much like that of the Show-Command dialog box. The completed command can be run or copied into
the ISE’s active pane.
Notice that Show-Command also exposes the Windows PowerShell common parameters, which are a set
of parameters that the shell adds to all commands to provide a specific set of consistent, baseline
functionality. You will learn more about many of the common parameters in upcoming modules.
However, if you want to read about them immediately, you can run help about_common_parameters in
the shell.
Demonstration Steps
1. Display the list of parameters available for use with the Get-Service cmdlet using the command
Show-Command.
3. Run the command, or copy it to the Clipboard and paste it into the shell for review.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 01-23
Each command has an internal setting called it’s confirm impact. This is set by the command’s developer
to Low, Medium, or High. Windows PowerShell has two built-in preference variables, or settings, that
interact with the confirm impact and the confirmation behavior. These preference variables are named
$ConfirmPreference and $WhatIfPreference, and when you open a new shell session, they are each set
to High by default. You may change them to Low or Medium. For example:
$ConfirmPreference = "Medium"
You should be aware that your changes affect only the current shell session; other open sessions are not
affected, and your change is lost when you close the current session.
Windows PowerShell’s confirmation behavior works as follows: when the command is run, Windows
PowerShell checks it’s internal confirm impact level. If that level is equal to or higher than the appropriate
preference variable, Windows PowerShell performs the confirmation action automatically.
For example, suppose that a command has a confirm impact of Medium, and you set
$ConfirmPreference to Low. When the command runs, the shell will see that its impact is higher than
the preference and will act as if you had used –Confirm. This means that you will be prompted to
continue or to halt the command.
If a command has an internal confirm impact of High, that command will always autoconfirm. You can
override this by specifying –Confirm:$false.
Demonstration Steps
1. Run Stop-Service by using –WhatIf on the BITS service.
Question: Are –WhatIf and –Confirm supported by all commands that modify the system
state or configuration in some way?
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 01-25
Objectives
After completing this lab, students will be able to:
• Use Windows PowerShell “About” topics to learn new shell concepts and techniques
Lab Setup
Estimated Time: 45 minutes
Password: Pa$$w0rd
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must
follow these steps:
1. On the host computer, move the pointer over the bottom left corner of the taskbar, click Start, and
then click Hyper-V Manager on the Start screen.
2. In Hyper-V® Manager, click 10961A-LON-DC1, and in the Actions pane, click Start.
3. In the Actions pane, click Connect. Wait until the virtual machine starts.
o Password: Pa$$w0rd
o Domain: ADATUM
In your tasks, italicized terms are intended to be keyword clues to help you complete the task.
2. What command would you run to make changes to a network adapter? After finding a command
that would make changes to a network adapter, what parameter would you use to change its MAC
Address (on adapters that support having their MAC address changed)?
3. What command would let you enable a previously disabled scheduled task?
4. What command would let you block access to a file share by a particular user?
5. What command would you run to clear your computer’s local BranchCache cache?
6. What command would you run to display a list of Windows Firewall rules? What parameter of that
command would display only enabled rules?
7. What command would you run to display a list of all locally bound IP addresses?
8. What command would you run to suspend an active print job in a print queue?
9. What native Windows PowerShell command would you run to format a new disk volume?
Results: After completing this exercise, you will have demonstrated your ability to use the command
discoverability features of Windows PowerShell™ to find new commands that perform specific tasks.
6. Locate the Background Intelligence Transfer Service (BITS) and note its startup type setting prior to
and after changing the startup type in Windows PowerShell.
7. Test the network connection to the computer named LON-DC1. Your command should return only a
True or False value, without any other output.
8. Display the newest 10 entries from the local Security event log.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 01-27
Results: After completing this exercise, you will have demonstrated your ability to run Windows
PowerShell commands by using correct command-line syntax.
Words in italic are intended as clues. Remember that you have to use Help (or Get-Help) and wildcard
characters. Because “About” files are not commands, Get-Command will not be useful in this exercise.
2. What comparison operator does Windows PowerShell use for wildcard string comparisons?
3. Are Windows PowerShell comparison operators typically case-sensitive?
4. How would you use $Env to display the COMPUTERNAME environment variable?
5. What external command could be used to create a self-signed digital certificate usable for signing
Windows PowerShell scripts?
6. Windows PowerShell 3.0 includes at least how many more new features than the earlier version?
2. In the Virtual Machines list, right click 10961A-LON-DC1, and then click Revert.
Results: After completing this exercise, you will have demonstrated your ability to locate Help content in
“About” files.
When you discover a new command, either by using Help or Get-Command, or by reading
about the command someplace, always take a moment to read the command’s Help file and
learn a bit about its additional capabilities.
Best Practice:
Even familiar commands can gain new functionality in new versions of Windows PowerShell. Take
several minutes to read the Help files even of commands that you already know well from earlier
versions, to see what new features may exist.
Module02
Working with the Pipeline
Contents:
Module Overview 02-1
Module Overview
Windows PowerShell™ is not the first command-line shell to support the concept of a pipeline. For
example, the command prompt in the Windows® operating system supports a pipeline. However,
Windows PowerShell’s pipeline is more complex, more flexible, and more capable than that of older shells.
The pipeline is a key concept and functional component of Windows PowerShell, and mastering it will
help you use the shell more effectively and efficiently.
Objectives
After completing this module, students will be able to:
Lesson 1
Understanding the Pipeline
In this lesson, you will learn about the Windows PowerShell pipeline. You will also learn the basic
techniques for running multiple commands in the Windows PowerShell pipeline.
Lesson Objectives
After completing this lesson, students will be able to:
• Explain the possible problems of running commands that produce more than one kind of object
As you interact with Windows PowerShell in the console host application, you can think of each command
line as a single pipeline. You type one or more commands and press Enter to run the pipeline. The output
of the last command in the pipeline appears on your screen. That output is followed by another shell
prompt, at which you can enter commands into a new pipeline.
Note: You can type a single logical command line over multiple physical lines in the
console. For example, type Get-Service ' and press Enter. The shell will enter an extended
prompt mode, indicated by the presence of the symbols >>. This enables you to complete the
command line. For now, press Ctrl+C to exit the command and return to the shell prompt.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 02-3
Note: Out-File will create a text file that has contents that match what would have
otherwise appeared on the screen. As an alternative, Windows PowerShell lets you use the
greater than symbol (>) instead. For example, Get-Service > ServiceList.txt will create a service
list in a text file that is named ServiceList.txt.
Pipeline Output
Most Windows PowerShell commands do not
generate text as output. Instead, they generate
objects. Object is a generic word that describes a
kind of in-memory data structure.
You can imagine command output looking like a
table, or a Microsoft® Office Excel spreadsheet. In
Windows PowerShell terminology, the table or
spreadsheet is a collection of objects, or just
collection for short. Each row is a single object, and
each column is a property. When you run Get-
Service, the command produces a collection of
service objects. Each has properties like Name,
DisplayName, Status, and so on.
Windows PowerShell’s use of objects is very different from other command-line shells whose commands
primarily generate text. In a text-based shell, suppose that you wanted to obtain a list of all services that
were started. You might run a command to produce a text list of services. You would then pipe that text
to a second command by using parameters to define a particular column position that contains status
information. If the output of the first command ever changed, and the status information moved, you
would have to rewrite the second command to have the new position information. Text-based shells
frequently require great skill with text parsing. This makes scripting languages such as Perl popular,
because it offers strong text parsing and text manipulation features.
In Windows PowerShell, you would just tell the shell to produce a collection of service objects, and to then
display only the Name property. The structure of the objects in memory enables the shell to find the
information for you, instead of you having to worry about the exact form of the command output.
MCT USE ONLY. STUDENT USE PROHIBITED
02-4 Working with the Pipeline
Windows PowerShell primarily deals with properties and methods. For most commands that you run, the
default on-screen output does not include all an object’s properties. Some objects have hundreds of
properties, and they would not all fit on the screen at one time. Windows PowerShell includes several
configuration files that list the object properties that should be displayed by default. That is why you see
three properties when you run Get-Service.
You can use the Get-Member command to list all the members of an object. It will list all properties, even
those that are not displayed on the screen by default. This command will also list methods and events and
show you the type name of the object. For example, the objects produced by Get-Service have the type
name System.ServiceProcess.ServiceController. You can use the type name in Internet search queries to
locate object documentation and examples (although those examples will frequently be in a
programming language such as Microsoft Visual Basic® or Microsoft Visual C#®).
Get-Service | Get-Member
Note: The first command will actually run, produce its output, and the pass that output to
Get-Member. Use caution when you run commands that may modify the system configuration,
because those commands will actually be running. You cannot use the –WhatIf parameter on
any command that you want to pipe to Get-Member, because the parameter prevents the
command from producing any output. That means Get-Member is given no input. Therefore, it
will display no output.
Demonstration Steps
1. Display a list of services.
5. Display the most recent five entries from the Security event log in a grid view.
7. For the objects produced by Get-NetAdapter, determine which property lists the adapter’s
maximum speed.
Note: If you pipe multiple kinds of objects to Get-Member, the command will display the
members for each kind of object separately. For example, piping Get-EventLog to Get-Member
can produce a large amount of output because each kind of event log entry is seen by Get-
Member as a different kind of object.
Question: Where could you find additional documentation about an object’s members?
MCT USE ONLY. STUDENT USE PROHIBITED
02-6 Working with the Pipeline
Lesson 2
Selecting, Sorting, and Measuring Objects
In this lesson, you will learn to manipulate objects in the pipeline by using commands that sort, select, and
measure.
Lesson Objectives
After completing this lesson, students will be able to:
Some examples:
By default, string properties are sorted without regard to case. In other words, lowercase and uppercase
letters are treated the same. Parameters of Sort-Object enable you to specify a case-sensitive sort, a
specific culture’s sorting rules, and other options.
Demonstration Steps
1. Display a list of processes sorted by process ID.
3. Display a list of the most recent 10 Security event log entries, sorted with the oldest entry first.
Measuring Objects
The Measure-Object command can accept any
kind of object in a collection. By default, the
command counts the number of objects in the
collection and produces a measurement object
that includes the count.
Note: Because Windows PowerShell enables you to truncate parameter names, you will
frequently see those written as –Sum, -Min, and –Max, corresponding to common English
abbreviations for those words. However, -Average cannot be shorted to –Avg, although
beginning users frequently try. The parameter could be shorted to –Ave, because that is a legal
truncation of the name.
Demonstration Steps
1. Display the number of services on your computer.
To select the 5 processes using the least amount of CPU, but skipping the one process using the least
CPU:
Best Practice: Always review property names in the output of Get-Member before you use
those property names in another command. Doing this guarantees that you are using the actual
property name and not a made-up name created for display purposes.
Note: The output of that command might look odd. By default, Windows PowerShell tries
to fill the width of your console window by spreading out table columns. When you display only
some columns, the resulting output contains a large amount of space in between the columns. In
Module 5, “Formatting Output,” you will learn how to gain more precise control over the output
display.
You can also specify a wildcard pattern for a property name, although if that results in lots of properties
being selected, some of those properties may be truncated because of screen space:
Demonstration Steps
1. Display the 10 largest processes by virtual memory use.
3. Display the 10 most recent Security event log entries. Include only the event ID, time written, and
event message.
items, and each item consists of a key and a value. Windows PowerShell uses hash tables many times and
for many purposes. In some cases, you can specify your own keys. When a hash table is used to create
calculated properties by using Select-Object, you must use the keys that Windows PowerShell expects.
Those are as follows:
• label, l, name, or n to specify the label of the calculated property. Because the lowercase L resembles
the number 1 in some fonts, try to use either name, n, or label.
Note: This book will use n and e for most examples because those two use less space on
the page.
For example, suppose that you want to display a list of processes that includes each process’ name, ID,
virtual memory use, and paged memory use. You want to use the column labels VirtualMemory and
PagedMemory for the last two properties, and you want those values displayed in bytes. You could run
the following command:
Get-Process |
Select-Object
Name,ID,@{n='VirtualMemory';e={$PSItem.VM}},@{n='PagedMemory';e={$PSItem.PM}}
Note: If you type that command exactly as is, pressing Enter after the vertical pipe
character, it will still work. You will enter extended prompt mode. After you type the rest of the
command, press Enter on a blank line to execute the command.
That command includes two hash tables, each one creating a calculated property. $PSItem is a special
variable created by Windows PowerShell. It represents whatever object was piped into the Select-Object
command. In this example, that is a Process object. The period after $PSItem lets you access a single
member of the object. In this example, one calculated property is using the VM property, and the other is
using the PM property. The hash table can be easier to interpret if you write it out a bit differently:
@{
n='VirtualMemory';
e={ $PSItem.VM }
}
As you can see, a semicolon separates the two key-value pairs. The keys n and e were used. These keys are
expected by Windows PowerShell. The label (or name) is just a string. Therefore, it is enclosed in quotation
marks. Windows PowerShell accepts either single or double quotation marks for this purpose. The
expression is a small piece of executable code called a script block, and is contained within curly braces.
Note: Earlier versions of Windows PowerShell used $_ instead of $PSItem. That older
syntax is compatible in Windows PowerShell 3.0, and many experienced users continue to use it
out of habit.
A comma separates each property from the others in the list. Name, ID, and both calculated properties are
all separated by commas.
Formatting Tips
You might want to modify the previous command to display memory values in megabytes (MB). Windows
PowerShell understands the abbreviations KB, MB, GB, TB, and PB as representing the base-2 values
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 02-11
kilobyte, megabyte, gigabyte, terabyte, and petabyte, respectively. So you might modify your command
as follows:
Get-Process |
Select-Object Name,
ID,
@{n='VirtualMemory(MB)';e={$PSItem.VM / 1MB}},
@{n='PagedMemory(MB)';e={$PSItem.PM / 1MB}}
In addition to revised formatting that makes the command easier to read, this new example changes the
column labels to include the MB designation. It also changes the expressions to include a division
operation, dividing each memory value by 1 MB. Unfortunately, the resulting values have several decimal
places, which is unattractive.
Get-Process |
Select-Object Name,
ID,
@{n='VirtualMemory(MB)';e={'{0:N2}' –f ($PSItem.VM / 1MB) }},
@{n='PagedMemory(MB)';e={'{0:N2}' –f ($PSItem.PM / 1MB) }}
This new example uses Windows PowerShell’s –f formatting operator. To the left of the operator is a string
that tells Windows PowerShell what data to display. {0:N2} means to display the first data item as a
number with two decimal places. To the right of the operator is the original mathematical expression. It is
in parentheses to make sure that it executes as a single unit. You can type this command exactly as shown,
press Enter on a blank line, and view the results.
The syntax in that example can be confusing because there are a lot of punctuation symbols. Start with
the basic expression:
This expression divides the VM property by 1 MB, and then formats that as a number having up to two
decimal places. That expression is then placed into the hash table:
Note: You can read more about the –f operator by running Help About_Operators in
Windows PowerShell.
Demonstration Steps
1. Display a list of the most recent commands run in the shell.
3. Locate the properties that contain the time that the command started running and the time that it
finished running.
MCT USE ONLY. STUDENT USE PROHIBITED
02-12 Working with the Pipeline
4. Display the same list, adding a calculated property that shows the time that it took each command to
run.
5. Display the same list, sorting the results by the time that it took each command to run. Show longest-
running commands at the top of the list, and shortest-running commands at the bottom.
Objectives
After completing this lab, students will be able to:
Lab Setup
Estimated Time: 30 minutes
Password: Pa$$w0rd
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must
complete the following steps:
1. On the host computer, move the pointer over the bottom left corner of the taskbar, click Start, and
then click Hyper-V Manager on the Start screen.
2. In Hyper-V® Manager, click 10961A-LON-DC1, and in the Actions pane, click Start.
3. In the Actions pane, click Connect. Wait until the virtual machine starts.
4. Sign in by using the following credentials:
o Password: Pa$$w0rd
o Domain: ADATUM
2. Using a keyword like date, find a command that can display the current date.
3. Display the members of the object produced by the command that you found in the previous step.
2. Display the members of the object produced by the command that you found in the previous step.
3. Display a list of installed hotfixes. Display only the installation date, the hotfix ID number, and the
name of the user who installed the hotfix.
4. Display a list of available IPv4 DHCP scopes. Include only the scope ID, subnet mask, and scope name.
5. Display a list of enabled firewall rules. Display only the rules’ display names, the profile they belong
to, their direction, and whether they allow or deny access. Sort the list in alphabetical order by display
name.
5. Display a list of network neighbors, sorted by state and displaying only the IP address and state.
2. Ping LON-CL1.
3. Using a keyword such as cache, find a command that can display items from the DNS client cache.
5. Display the DNS client cache. Sort the list by record name, and display only the record name, record
type, and time to live.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 02-15
Results: After completing this exercise, you will have produced several custom reports that contain
management information from your environment.
Question: Suppose that you wanted to produce output that included all of an object’s
properties except one. What would be the most efficient way to do that?
MCT USE ONLY. STUDENT USE PROHIBITED
02-16 Working with the Pipeline
Lesson 3
Converting, Exporting, and Importing Objects
In this lesson, you will learn about Windows PowerShell’s built-in features for converting data to different
formats, and for exporting and importing data from and to external storage.
Lesson Objectives
After completing this lesson, students will be able to:
A command that uses the verb Export, such as Export-CSV, performs two operations at the same time. It
first converts the data, and then it writes the data to external storage that might be a file on disk. For
example:
Export commands basically combine the functionality of ConvertTo with a command like Out-File.
Export commands do not usually put any output into the pipeline. Therefore, nothing appears on the
screen after an export command finishes running.
A key part of both operations is that the form of the data is changed to something like CSV, XML, HTML,
or another form. The data is no longer contained in the structure referred to as objects, and is instead
represented in another form entirely. When you convert it to another form, data is generally more difficult
to manipulate. Converted data cannot be easily sorted, selected, measured, and so on.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 02-17
To see a list of commands, run Get-Command –Verb ConvertTo,Export. The commands that you will
use most frequently include the following:
• ConvertTo-CSV
• ConvertTo-HTML
• ConvertTo-XML
• Export-CSV
• Export-CliXML
Various parameters of Out-File enable you to specify a file name, to append content to an existing file, to
specify character encoding, and so on.
Out-File is perhaps the easiest way to move data out of the shell and into external storage. However,
because the text files that Out-File creates are usually intended for viewing by a person, reading the data
back into the shell in any way that enables the data to be manipulated, sorted, selected, measured, and so
on is frequently difficult or impractical.
Out-File does not produce any output of its own. This means that the command does not put objects
into the pipeline. After you run the command, you should expect to see no output on the screen.
Get-Service |
Sort-Object –Property Status |
Select-Object –Property Name,Status |
ConvertTo-CSV |
Out-File –FilePath ServiceList.csv
MCT USE ONLY. STUDENT USE PROHIBITED
02-18 Working with the Pipeline
The preceding example contains five commands in a single command line or pipeline.
• After Sort-Object runs, the pipeline still contains those ServiceController objects. Sort-Object
produces output that is the same kind of object that was put into it.
• After Select-Object runs, the pipeline no longer contains ServiceController objects. Instead, it
contains objects of the type Selected.System.ServiceProcess.ServiceController. This behavior
indicates that the objects derive from the regular ServiceController but have had some of their
members removed. In this case, the objects contain only their Name and Status properties, so you
could no longer sort them on their DisplayName, because that property no longer exists.
• After ConvertTo-CSV runs, the pipeline contains System.String objects that contain the CSV-
formatted data. Windows PowerShell could no longer sort or select these objects, because they are
no longer in a dedicated kind of object.
• After Out-File runs, the pipeline contains nothing. Therefore, nothing will appear on the screen after
running this complete command.
Note: When you have a complex, multiple command pipeline such as this one, you may
have to debug it if it does not run correctly the first time. The best way to debug is to start with
just one command, and see what it produces. Then add the second command, and see what
happens. Continue to add one command at a time, verifying that each one produces the output
you expected before you add the next command.
Demonstration Steps
1. Convert a list of processes to HTML.
2. Create a file that is named Procs.html that contains an HTML-formatted list of processes.
3. Convert a list of services to CSV.
4. Create a file that is named Serv.csv that contains a CSV-formatted list of services.
5. Open Serv.csv in Notepad and decide whether all the data was retained.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 02-19
Importing Data
Importing is the process of reading formatted
data from external storage, such as a file on disk,
and converting that data back into objects. Those
objects are usually put into the pipeline, where
they can be passed to other commands for
additional manipulation.
You have already learned that the Export verb in Windows PowerShell implies a two-step process: data is
first converted to another form, and then it is written to external storage. The Import verb also implies a
two-step process: data is first read from external storage, and then it is converted from that format into
objects. For example:
This command saves a list of running processes in CSV format, in a file that is named Processes.csv. Here is
the next command:
This command reads that CSV file, reconstructs the original objects with some degree of fidelity, sorts
those objects in descending order on their VM property, and then selects the first 10 objects.
Importing implies that the command understands the form that the data is in, and that the command can
construct usable objects from that data. Importing differs from reading a file’s contents and not paying
attention to the form. For example:
This command will not produce the expected results. Instead of importing the data, the Get-Content
command was used to read it. Using Get-Content resembles looking at a CSV file in Notepad, where you
see the raw data. Importing is more like importing a CSV file into Microsoft Office Excel, where the file is
interpreted and correctly broken out into various rows and columns in a spreadsheet.
Because Get-Content does not try to interpret the file, Windows PowerShell includes several commands
that use the ConvertFrom verb. As the name implies, these commands are the opposite of those that use
the ConvertTo verb. For example:
This command would have the result you want, because Get-Content is being used to read the file’s raw
contents, but then ConvertFrom-CSV is interpreting that data and constructing usable objects to put into
the pipeline. Used together in this manner, Get-Content and ConvertFrom-CSV have the same result as
Import-CSV.
MCT USE ONLY. STUDENT USE PROHIBITED
02-20 Working with the Pipeline
Note: In many cases, two commands might achieve the same result as one, but they may
take longer to run. For example, Import-CSV alone runs faster than Get-Content and
ConvertFrom-CSV combined.
Demonstration Steps
1. Read the contents of Serv.csv without interpreting the data.
2. Import the contents of Serv.csv so that the data is interpreted into objects.
3. Using the services in Serv.csv, display a list of services that have running services listed first, stopped
services listed second, and services sorted in reverse alphabetical order, by name, within those lists.
Display only service names and status.
Question: What other data forms might you want to convert data to or from?
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 02-21
Objectives
After completing this lab, students will be able to:
Lab Setup
Estimated Time: 30 minutes
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must
follow these steps:
1. On the host computer, move the pointer over the bottom left corner of the taskbar, click Start, and
then click Hyper-V Manager on the Start screen.
2. In Hyper-V® Manager, click 10961A-LON-DC1, and in the Actions pane, click Start.
3. In the Actions pane, click Connect. Wait until the virtual machine starts.
o Domain: ADATUM
3. Display a list of running processes, sorted in reverse alphabetical order by process name that shows
only the process name, ID, virtual memory, and physical memory consumption.
MCT USE ONLY. STUDENT USE PROHIBITED
02-22 Working with the Pipeline
5. Display the same list again, and convert the list to an HTML page.
6. Display the same list again, and convert the list to an HTML page. Store the HTML in ProcReport.html.
8. Display the same list again, and convert it to HTML. Store the HTML in ProcReport.html, overwriting
the existing file. Have the phrase Processes appear before the list of processes. Have the current date
appear after the list of processes.
Results: After completing this exercise, you will have converted objects to different forms of data.
3. Produce a pipe-delimited list of the most recent 20 Security event log entries.
Task 1: Create a comma-separated values (CSV) file listing the most recent 10 entries
from the System event log.
1. Display the most recent 10 entries from the System event log.
2. Convert, but do not export, the event log list to CSV form.
3. Export the event log list to CSV form in a file that is named SysEvents.csv.
5. Create SysEvents.csv again, but remove the first line of the file that begins with #.
2. Export the list to an XML file that uses the command-line interface (CLI) XML (CliXML) format. Name
the file Services.xml.
4. Create the list again, but include only services’ names, display names, and status. Export the list to
CliXML in the file Services.xml.
Task 3: Produce a pipe-delimited list of the most recent 20 Security event log entries
1. View the Help for ConvertTo-CSV.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 02-23
3. Display the list again. Include only the event ID, time written, and message.
4. Export the list to a file that is delimited by using the vertical pipe (|) character. Name the file
Security.pdd.
Results: After completing this lab, you will have imported data from and exported data to external
storage.
Question: Could you use ConvertTo-CSV or Export-CSV to create a file that was delimited
by using a character other than a comma? For example, could you create a tab-delimited
file?
Question: The HTML produced by ConvertTo-HTML looks very plain. The HTML standard
offers a way to specify visual styles for an HTML document. This is known as a cascading style
sheet (CSS). Does the command offer a way to attach a CSS?
MCT USE ONLY. STUDENT USE PROHIBITED
02-24 Working with the Pipeline
Lesson 4
Filtering Objects Out of the Pipeline
In this lesson, you will learn how to filter objects out of the pipeline by specifying various criteria. This
differs from, and is more flexible than, the ability of Select-Object to select several objects from the
beginning or end of a collection. With this new technique, you will be able to keep or remove objects
based on criteria of almost any complexity.
Lesson Objectives
After completing this lesson, students will be able to:
Comparison Operators
To start filtering, you will need a way to tell
Windows PowerShell which objects that you want
to keep and which objects want to remove from
the pipeline. You do this by specifying criteria for
objects that you want to keep, and most of the
time, you will do so by using one of the shell’s
comparison operators. You will ask the shell to
compare some property of an object to some
value that you specify, and if the comparison is
true, the object is kept. If the comparison is false,
the object is removed.
• -eq equal to
Be aware that for string comparisons, these operators are all case-insensitive, meaning they are not
sensitive to case. A case-sensitive version of each is available if it is necessary, such as –ceq and -cne.
The shell also contains the –like operator and its case-sensitive companion, -clike. The -like operator
resembles –eq but supports the use of the question mark (?) and asterisk (*) wildcard characters in string
comparisons.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 02-25
There are additional, more advanced operators that will not be covered at this point. These include the
following:
Comparisons can be made directly at the command line prompt. For example:
This technique makes it easy to test comparisons before you use them in a command.
If you misspell the property name, or if you provide the name of a nonexistent property, Windows
PowerShell will not generate an error. Instead, your command will not generate any output. For example:
This command produces no output, because no service object had a Stat property that contained the
value Running. Actually, none of the service objects have a Stat property at all. This is why the
comparison returns False for every object.
Note: Because of the complex parameter sets needed to make the basic syntax functional,
the Help file for Where-Object is very long and difficult to read. Consider skipping the initial
Syntax section and going directly to the Description or Examples if you need help with this
command.
MCT USE ONLY. STUDENT USE PROHIBITED
02-26 Working with the Pipeline
The basic syntax cannot be used with complex expressions. For example, the Name property of a service
object is a string of characters. Windows PowerShell uses a System.String object to contain that string of
characters, and a System.String object has a Length property. The following will not work with the basic
filtering syntax:
The intent is to display all services that have a name longer than five characters. However, this command
will never produce output.
As soon as you exceed the capabilities of the basic syntax, you will have to move to the advanced filtering
syntax.
The –FilterScript parameter is positional, and most users will omit it. Most users will also use the Where
alias, or even the shorter ? alias. Experienced Windows PowerShell users will also use the $_ variable
instead of $PSItem, because only $_ was allowed in version 1.0 and 2.0 of the shell. Both of the following
commands perform the same task as the previous two commands:
The quotation marks around 'Running' in these examples are required. Otherwise, the shell will try to run
a command called Running, which would fail because no such command exists.
Multiple Criteria
The advanced syntax enables you to specify multiple criteria by using the –and and –or Boolean or logical
operators. For example:
The logical operator must have a complete comparison on either side of it. In this example, the first
comparison checked the EventID property, and the second comparison checked the EntryType property.
The following example is one that many beginning users try. It is incorrect because the second
comparison is incomplete.
The problem here is that VM has no meaning. $PSItem.VM would be correct. Here is another common
mistake:
The problem with that example is that 'Starting' is not a complete comparison. It is just a string value.
$PSItem.Status –eq 'Starting' would be the correct syntax for the intended result.
In the first command, the special shell variable $True is used to represent the Boolean value True. In the
second example, there is no comparison at all. The second example works because the Responding
property already contains True or False.
Reversing the logic to list only processes that are not responding looks similar:
In this example, the –not logical operator changes True to False and changes False to True. Therefore, if a
process is not responding, its Responding property would be False. The –not operator changes that to
True, which causes the process to be generated into the pipeline and included in the final output of the
command.
Demonstration: Filtering
In this demonstration, you will see various ways to filter objects out of the pipeline.
MCT USE ONLY. STUDENT USE PROHIBITED
02-28 Working with the Pipeline
Demonstration Steps
1. Use basic filtering syntax to display a list of SMB shares that include a dollar sign ($) in their share
name.
2. Use advanced filtering syntax to display a list of physical disks that are in healthy condition.
3. Display a list of disk volumes that are fixed disks and that use the NTFS file system.
4. Using advanced filtering syntax and without using the $PSItem variable, display a list of Windows
PowerShell command verbs that begin with the letter C.
The second command would be faster, because it removes unwanted blocks from the pipeline. The first
command sorts all the blocks, and then removes many of them. This means that much of the sorting
effort was wasted.
There is a mnemonic used by many Windows PowerShell users to help them remember to do the correct
thing when they are optimizing performance. The phrase is filter left, and it means that any filtering
should occur as far to the left, or as close to the beginning of the command line, as possible.
Sometimes, moving filtering as far to the left as possible means that you will not use Where-Object. For
example, the Get-ChildItem command can produce a list that includes files and folders. Each object
produced by the command has a property named PSIsContainer. It contains True if the object represents
a folder and False if the object represents a file. The following command will produce a list that includes
only files:
However, that is not the most efficient way to produce the result. The Get-ChildItem command has a
parameter that limits the command’s output:
Get-ChildItem -File
When it is possible, check the Help files for the commands that you use to see whether they contain a
parameter that can do the filtering you want. Here is another example:
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 02-29
Is this the most efficient way to produce a list of services whose names start with svc? No. Here is a better
approach:
Objectives
After completing this lab, students will be able to:
• Filter objects out of the pipeline by using basic and advanced syntax forms
Lab Setup
Estimated Time: 30 minutes
Password: Pa$$w0rd
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must
follow these steps:
1. On the host computer, move the pointer over the bottom left corner of the taskbar, click Start, and
then click Hyper-V Manager on the Start screen.
2. In Hyper-V® Manager, click 10961A-LON-DC1, and in the Actions pane, click Start.
3. In the Actions pane, click Connect. Wait until the virtual machine starts.
4. Sign in by using the following credentials:
o Password: Pa$$w0rd
o Domain: ADATUM
Some tasks in this exercise will require you to filter based on date and time information. You should
already know a command that can retrieve the current date and time. That command will usually have to
be executed enclosed in parentheses so that you can use its result, instead of the command itself, as a
comparison value. When you compare dates, any date in the future is considered greater than today’s
date. Any date in the past is considered less than today’s date.
You will also have to calculate free space percentages in this exercise. The mathematical formula to
calculate free space percentage is (Free Space / Size).
The main tasks for this exercise are as follows:
2. Create a report that shows Security event log entries having the event ID 4624
4. Create a report that shows disk volumes that are running low on space
Task 1: Display a list of all users in the Users container of Active Directory
1. Log on to the 10961A-LON-CL1 virtual machine logged in as Adatum\Administrator.
2. Using a keyword like user, find a command that can list Active Directory® users.
3. View the full Help for the command and identify any mandatory parameters.
Task 2: Create a report that shows Security event log entries having the event ID
4624
1. Display a list of Security event log entries that have the event ID 4624.
2. Display the list again and show only the time written, event ID, and message.
3. Produce the same list in an HTML file named EventReport.html.
3. Display the list again and show only certificates that do not have a private key.
4. Display the list again and show only certificates that have a NotBefore date that is before today, and
a NotAfter date that is after today. Include only certificates that do not have a private key.
5. Display the list again and show only the issuer name, NotAfter date, and NotBefore date for each
certificate.
Task 4: Create a report that shows disk volumes that are running low on space
1. Display a list of disk volumes.
2. Display a list that shows the members of the objects produced by the previous command.
3. Display a list of volumes that have more than zero bytes of free space.
4. Display a list of volumes that have less than 99 percent free space, and more than zero bytes of free
space.
5. Display a list of volumes that have less than 10 percent free space and more than zero bytes of free
space. This command may produce no results if no volumes on your computer meet the criteria.
Results: After completing this exercise, you will have used filtering to produce lists of management
information that include only specified data and elements.
Question: In the first task of this lab, were you able to achieve the goal without using the
Where-Object command?
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 02-33
Lesson 5
Enumerating Objects in the Pipeline
In this lesson, you will learn how to enumerate objects in the pipeline so that you can work with one
object at a time.
Lesson Objectives
After completing this lesson, students will be able to:
Consider the kind of object produced when you run Get-ChildItem –File on a disk drive. This object type,
System.IO.FileInfo, has a method named Encrypt() that can encrypt a file by using the current user
account’s encryption certificate. No equivalent command is built into Windows PowerShell, so you might
have to execute that method on many file objects that you wanted to encrypt. Enumeration enables you
to do this with a single command.
Enumeration is performed by the ForEach-Object command. It has two common aliases: ForEach and %.
MCT USE ONLY. STUDENT USE PROHIBITED
02-34 Working with the Pipeline
Note: You may not discover many scenarios where you have to use enumeration. Windows
8 and Windows Server® 2012, for example, introduced thousands of new Windows PowerShell
commands. Many of those new commands perform actions that previously required
enumeration.
Demonstration Steps
1. Display only the name of every service installed on the computer.
The ForEach-Object command (which has the aliases ForEach and %) can accept any number of objects
from the pipeline. It has a –Process parameter that accepts a script block. This script block will execute
one time for each object that was piped in. Every time that the script block executes, the built-in variable
$PSItem (or $_) can be used to refer to the current object. In the preceding example command, the
Encrypt() method of each file object is executed.
Note: When they are used with the advanced syntax, method names are always followed
by opening and closing parentheses, even when the method does not have any input arguments.
For methods that do need input arguments, provide them as a comma-separated list inside the
parentheses. You may not include a space or other characters between the method name and the
opening parentheses.
Advanced Techniques
In some situations, you may need to repeat a given task for a specified number of times. ForEach-Object
can be used for that purpose, when you use it at the same time as the range operator. For example:
In this command, the range operator is used to produce integer objects from 1 through 100. The range
operator is two periods (..) with no space in between them. Those 100 objects are piped to ForEach-
Object, forcing its script block to execute 100 times. However, because neither $_ nor $_PSItem appear in
the script block, the actual integers are not used. Instead, the command Get-Random is run 100 times.
The integer objects are used only to set the number of times the script block executes.
Demonstration Steps
1. Modify all items in the HKEY_CURRENT_USER\Network\ key so that all names are uppercase.
2. Produce a list of process names to a text file that is named Procs.txt. Include the current date at the
beginning of the file.
Objectives
After completing this lab, students will be able to:
Lab Setup
Estimated Time: 30 minutes
Password: Pa$$w0rd
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must
follow these steps:
1. On the host computer, move the pointer over the bottom left corner of the taskbar, click Start, and
then click Hyper-V Manager on the Start screen.
2. In Hyper-V® Manager, click 10961A-LON-CL1, and in the Actions pane, click Start.
3. In the Actions pane, click Connect. Wait until the virtual machine starts.
4. Sign in by using the following credentials:
o Password: Pa$$w0rd
o Domain: ADATUM
1. Display a list of key algorithms for all encryption certificates installed on your computer.
Task 1: Display a list of key algorithms for all encryption certificates installed on your
computer.
1. Display a directory listing of all items in the CERT: drive. Include subfolders in the list.
3. In the member list, find a method that will retrieve the key algorithm for a certificate.
5. Using Select-Object instead of ForEach-Object, display a list of all certificates on the computer.
Display only columns named Issuer and KeyAlgorithm. The KeyAlgorithm column should be a
calculated column that uses the method that you discovered in step 3.
4. Run the command again. For each numeric object, produce a random number that uses the numeric
object as a seed.
4. In the member list, find a method that will restart the computer.
5. Run the command again and use enumeration to execute the method that will restart the computer.
Results: After completing this exercise, you will have written commands that manipulate multiple objects
in the pipeline.
For best performance, remember to move filtering actions as close to the beginning of the
command-line as possible. Sometimes that may mean using a filtering capability of a regular
command, instead of using Where-Object.
$_ is confusing to read.
Review Question(s)
Question: $_ and $PSItem were used several times in this module. Why might you decide to
use one over the other?
In Windows PowerShell 3.0, these five commands produce the same result: a list of service names. As you
explore Windows PowerShell, and especially as you read examples written by other people or provided by
your instructor, you should be aware that there is not only one correct way to use Windows PowerShell.
Part of using the shell is being able to understand many approaches, arrangements of syntax, and
techniques.
MCT USE ONLY. STUDENT USE PROHIBITED
03-1
Module03
Understanding How the Pipeline Works
Contents:
Module Overview 03-1
Module Overview
In this module, you will learn how Windows PowerShell™ passes objects from one command to another in
the pipeline. The shell has two techniques it can use. Knowing how these techniques work, and which one
will be used in a given scenario, lets you construct more useful and complex command lines.
Additional Reading: You can read more about how the pipeline works at
http://technet.microsoft.com/en-us/library/ee176927.aspx.
Objectives
After completing this module, students will be able to:
• Pass data by using the ByValue technique
Lesson 1
Passing Data in the Pipeline By Value
In this lesson, you will learn about the first of Windows PowerShell’s pipeline techniques. Called ByValue,
it is the first technique the shell tries to use.
Lesson Objectives
After completing this lesson, students will be able to:
Basically, when two commands are connected in the pipeline, pipeline parameter binding has to take the
output of the first command and decide what to do with it. The process has to select one of the
parameters of the second command to receive those objects. The shell has two techniques that it uses to
make that decision. The first technique, and the one that the shell always tries to use first, is called
ByValue. The second technique is called ByPropertyName and is only used when ByValue fails.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 03-3
-InputObject <PSObject>
Specifies the objects to be
sorted.
To sort objects, pipe them to
Sort-Object.
Required? false
Position? named
Default value
Accept pipeline input? true
(ByValue)
Accept wildcard characters? false
The Accept pipeline input? attribute is true because the –InputObject parameter accepts pipeline input.
Also shown is a list of the techniques the parameter supports. In this case, it supports only the ByValue
technique.
'BITS','WinRM' | Get-Service
Here, two string objects are being piped into Get-Service. They will be attached to the –Name
parameter, because that parameter accepts that kind of object, ByValue, from the pipeline.
The key to predicting what the shell will do with objects in the pipeline is knowing what kind of object is
in the pipeline. To do that, you can pipe the object to Get-Member. The first line of output will tell you
what kind of object the pipeline contained. For example:
Here, the pipeline contained objects of the type System.String. Windows PowerShell frequently
abbreviates type names to include only the last portion. In this example, that would be String.
Then you examine the full Help for the next command in the pipeline. In this example, it is Get-Service,
and you would find that both the –InputObject and –Name parameters accept input from the pipeline
ByValue. Because the pipeline contains objects of the type String, and because the –Name parameter
accepts objects of the type String from the pipeline ByValue, the objects in the pipeline are attached to
the –Name parameter.
If there is no match for a specific data type, the shell will try to match generic data types. That behavior is
why commands like Sort-Object and Select-Object work. Those commands each have a parameter
named –InputObject that accepts objects of the type PSObject from the pipeline ByValue. That is why
you can pipe anything to those commands. Their –InputObject parameter will receive anything from the
pipeline, because it accepts objects of any kind.
Demonstration Steps
1. Look at this example command:
4. Decide what parameter of the second command in step 1 will receive the output of the first
command.
Windows PowerShell would typically attach those strings to the –Name parameter of Get-Service.
However, in this example, the –Name parameter was already used manually. That puts a stop to pipeline
parameter binding. The shell will not look for another possible parameter to bind the input to. The
parameter it wanted to use is taken, so that the process is over.
The error is misleading. It says that the command does not take pipeline input. However, the command
usually does. In this example, you have disabled the command’s ability to accept the pipeline input
because you manually specified the parameter that the shell wanted to use.
Demonstration Steps
1. Pipe two strings to display a list of two services.
2. Pipe two strings to display a list of services, but manually specify a service name.
However, the following command does not work, because the second command was not designed to
accept the pipeline input provided:
A parenthetical command is a command that is enclosed in parentheses. Just as in math, parentheses tell
the shell to “do this first.” The parenthetical command runs, and the results of the command are inserted
in its place. In this example, the contents of the ProcessNames.txt file would be inserted as input to the –
Name parameter.
Parenthetical commands do not rely on pipeline parameter binding. They work with any parameter as
long as the parenthetical command produces the kind of object that the parameter expects.
Demonstration Steps
1. Create a text file that contains LON-CL1 on one line, and localhost on the other.
3. Use a parenthetical expression to display a list of services that are running on LON-CL1 and localhost.
Question: Why do most commands that use the noun Object have an –InputObject
parameter that accepts objects of the type Object or PSObject?
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 03-7
Lesson 2
Passing Data in the Pipeline By Property Name
In this lesson, you will learn about the ByPropertyName technique of passing data in the pipeline. This is
the second technique that Windows PowerShell tries to use.
Lesson Objectives
After completing this lesson, students will be able to:
Changing to ByPropertyName
If Windows PowerShell is unable to bind pipeline
input by using the ByValue technique, it tries to
use the ByPropertyName technique.
For example:
Get-Service | Stop-Process
The shell changes to the ByPropertyName technique. To predict what it will do, you must review the
properties of the objects produced by the first command. In this example, you would run:
Get-Service | Get-Member
You would also have to make a list of parameters, of the second command, that can accept pipeline input
by using ByPropertyName. To make that list, view the Help for the second command:
In this example, the Stop-Process command has more than one parameter that accepts pipeline input by
using ByPropertyName. Those parameters are –Name and –Id. The objects produced by Get-Service do
not have an ID property. So, the –Id parameter is not considered. The objects produced by Get-Service
have a Name property. Therefore, the contents of the Name property are attached to the –Name
parameter.
MCT USE ONLY. STUDENT USE PROHIBITED
03-8 Understanding How the Pipeline Works
Note: The ByPropertyName technique is very simplistic. Because the property Name and
the parameter –Name are spelled the same, and because the parameter was programmed to
accept input in this manner, they connect to one another.
Demonstration Steps
1. Display the contents of a comma-separated value (CSV) file that contains new user information.
2. View the Help for New-ADUser and locate parameters that can accept pipeline input.
3. Using –WhatIf, create new users by using the information in the CSV file.
4. View a second CSV file that represents a more real-world scenario.
5. Run a command that imports the second CSV file, modifies the objects, and creates new Active
Directory® users.
6. Verify that the new users were created.
Get-ADComputer –filter *
However, that command produces objects of the type ADComputer. You could not use those objects
directly in a parenthetical command such as this one:
The –ComputerName parameter expects objects of the type String. But that is not what the
parenthetical command is producing. Basically, the –ComputerName parameter just wants a computer
name. However, you are giving it an object that contains a name, an operating system version, and several
other properties.
That command selects only the Name property. But that property is still a member of a whole
ADComputer object. It is the Name property of an object. Although the Name property contains a
string, it is not itself a string. The –ComputerName parameter expects a string, not an object having a
property.
This command will achieve the goal:
The –ExpandProperty parameter accepts one, and only one, property name. When you use that
parameter, only the contents of the specified property are produced by Select-Object. Some people refer
to this as extracting the property contents. The official description of the feature is expanding the property
contents.
In the preceding command, the result of the parenthetical command is a collection of strings, and that is
what the –ComputerName parameter expects. The command will work correctly, although of course it
may produce an error if one or more of the computers cannot be reached on the network.
Demonstration Steps
1. Open the Windows PowerShell Integrated Scripting Environment (ISE).
3. Run a command that uses a parenthetical command to display a list of services from every computer
in the domain.
4. Run a command that shows the kind of object produced when you retrieve every computer from the
domain.
5. Review the help for Get-Service to see what kind of object its –ComputerName parameter expects.
6. Run a command that selects only the Name property of every computer in the domain.
7. Run a command that shows the kind of object produced by the previous command.
MCT USE ONLY. STUDENT USE PROHIBITED
03-10 Understanding How the Pipeline Works
8. Run a command that extracts the contents of the Name property of every computer in the domain.
9. Run a command that shows the kind of object produced by the previous command.
10. Modify the command in step 3 to use the command in step 8 as the parenthetical command.
Question: Can correct use of pipeline parameter binding reduce the need to use ForEach-
Object?
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 03-11
Objectives
After completing this lab, students will be able to:
Lab Setup
Estimated Time: 45 minutes
The changes that you make during this lab will be lost if you revert your virtual machines at another time
during class.
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must
follow these steps:
1. On the host computer, move the pointer over the bottom left corner of the taskbar, click Start, and
then click Hyper-V Manager on the Start screen.
2. In Hyper-V® Manager, click 10961A-LON-DC1, and in the Actions pane, click Start.
3. In the Actions pane, click Connect. Wait until the virtual machine starts.
4. Sign in by using the following credentials:
o Password: Pa$$w0rd
o Domain: ADATUM
6. This lab can be performed with the use of the 10961A-LON_CL1 virtual machine.
1. This command is intended to list the services that are running on every computer in the domain:
Get-ADComputer –Filter * |
Get-Service
2. This command is intended to list the services that are running on every computer in the domain:
Get-ADComputer –Filter * |
Select @{n='ComputerName';e={$PSItem.Name}} |
Get-Service
3. This command is intended to query an object from every computer in the domain:
Get-ADComputer –Filter * |
Select @{n='ComputerName';e={$PSItem.Name}} |
Get-WmiObject –Class Win32_BIOS
This command is intended to list the services that are running on every computer that is listed in
Names.txt.
Get-Content Names.txt |
Get-Service
This command is intended to list the services that are running on every computer that is listed in
Names.txt.
6. This command is intended to list the services that are running on every computer in the domain:
7. This command is intended to list the Security event log entries from every computer in the domain:
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 03-13
1. Write a command that uses Get-EventLog to display the most recent 50 System event log entries
from each computer in the domain.
2. You have a text file that is named Names.txt that contains one computer name per line. Write a
command that uses Restart-Computer to restart each computer that is listed in the file. Do not use a
parenthetical command.
3. You have a file that is named Names.txt that contains one computer name per line. Write a
command that uses Test-Connection to test the connectivity to each computer that is listed in the
file.
4. Write a command that uses Set-Service to set the start type of the WinRM service to Auto on every
computer in the domain. Do not use a parenthetical command.
2. In the Virtual Machines list, right click 10961A-LON-DC1, and then click Revert.
3. In the Revert Virtual Machine dialog box, click Revert.
Results: After completing this exercise, you will have reviewed and written several Windows PowerShell™
commands.
Question: Why do some commands accept pipeline input for a parameter such as –
ComputerName, but other commands do not?
Question: Do you ever have to rely on pipeline input? Could you just rely on parenthetical
commands?
MCT USE ONLY. STUDENT USE PROHIBITED
03-14 Understanding How the Pipeline Works
It is easy to start using Windows PowerShell and not think about what the shell is doing for you.
Always take a moment to examine each command that you write, and think about what the shell
will do. Think about what objects will be produced by each command, and how those will be
passed to the next command.
Review Question(s)
Question: Because pipeline input binding is handled invisibly by the shell, it can be difficult
to troubleshoot. Are there any tools that can help you troubleshoot pipeline input?
Module04
Using PSProviders and PSDrives
Contents:
Module Overview 04-1
Module Overview
In this module, you will learn to work with PSProviders and PSDrives. A PSProvider is basically a
Windows PowerShell™ adapter that makes some form of storage resemble a disk drive. A PSDrive is an
actual connection to a form of storage. These two technologies let you work with many forms of storage
by using the same commands and techniques that you use to manage the file system.
Additional Reading: You can read more about providers and drives, and how to manage
them, at http://technet.microsoft.com/en-us/library/dd315335.aspx.
Objectives
After completing this module, students will be able to:
Lesson 1
Using PSProviders
In this lesson, you will learn about PSProviders, which are the adapters that connect Windows PowerShell
to data stores.
Lesson Objectives
After completing this lesson, students will be able to:
Managing a technology by using a provider is somewhat more difficult than managing by using
commands. Commands are typically specific, and the command name describes what the command does.
For example, in Microsoft® Exchange Server 2007 and newer versions, the Get-Mailbox command
retrieves mailbox objects. If that technology used a PSProvider instead, you might have to run a command
like Get-ChildItem EXCHANGE:\Server2\MailStore\Mailboxes instead.
Note: That command is just a theoretical example. Exchange Server is not managed by
using a PSProvider. However, you can see that managing by using a PSProvider looks somewhat
more complex.
The advantage of a PSProvider is that it is dynamic. For example, Microsoft cannot know in advance what
disk drives, folders, and files that you will install and create on a computer. The FileSystem PSProvider can
dynamically adapt to whatever each computer contains. Microsoft Internet Information Services (IIS) is
also managed, in part, by using a PSProvider. That provider can adapt to whatever Microsoft and third-
party add-ins are installed in IIS. Microsoft could not easily write commands to manage everything in IIS,
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 04-3
because new add-ins are created constantly. So even though management by using a provider is more
complex, it is a better strategy for dealing with dynamic and extensible technologies.
• ShouldProcess, for providers that can support the –WhatIf and –Confirm parameters
You should always review the capabilities of a provider before you work with it so that you will not
encounter unexpected errors by trying to use unsupported capabilities.
Demonstration Steps
1. Display a list of providers. Notice the capabilities listed for each one.
3. Display a list of providers. Notice the new provider added by the Active Directory module.
Question: What other kinds of PSProviders might exist as add-ins to the shell?
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 04-5
Lesson 2
Using PSDrives
In this lesson, you will learn how to work with PSDrives. A PSDrive represents a specific form of storage
that is connected to the shell by using a PSProvider.
Lesson Objectives
After completing this lesson, students will be able to:
To create a new connection, use the New-PSDrive command. You must specify a unique drive name, the
root location for the new drive, and the PSProvider that will be used to make the connection. Depending
on the capabilities of the PSProvider, you may also specify alternative credentials and other options.
Windows PowerShell always starts a new session with the same drives:
• Registry drives HKLM and HKCU
Note: Drive names do not include the colon. Drive name examples include Variable and
Alias. However, when you want to refer to a drive as a path, include the colon. For example,
Variable: refers to the drive Variable, just as C: refers to drive C. Commands like New-PSDrive
require a drive name. Do not include a colon in the drive name when using those commands.
Note: Because Windows PowerShell accepts a forward slash or backward slash as a path
separator, Dir /s is interpreted by the shell as “display a directory listing of the folder named s.”
Unless that folder exists, you will see an error when you run that command.
Notice that the Windows PowerShell cmdlet names all use generic nouns like Item and ItemProperty.
That is because the cmdlets are intended to work with any PSDrive connected by using any PSProvider. In
the file system, an item might be a file or a folder. In the registry, an item might be a key or a setting. In
the certificate store, an item might be a folder or a certificate. Instead of having separate commands for
all these items, Microsoft chose to create a single set of commands that uses generic nouns.
Windows PowerShell stores its own variables in a drive named Variable. With that piece of information,
what command would you run to delete a variable named X? The answer is Del Variable:\X. Because the
variable storage is made to resemble a disk drive, you manage it by using the same commands you would
use with a disk drive.
Note: You can even delete some of Windows PowerShell’s built-in variables. That action is
not permanent. Every time you start a new Windows PowerShell session, that session creates the
same default set of variables, with the same default values. So if you accidentally delete a built-in
variable, just close the session and open a new one.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 04-7
Specifying Paths
When you use commands that have the Item,
ChildItem, and ItemProperty nouns, you will
typically specify a path to tell the command what
item or items that you want to manipulate. Most
of these commands have two parameters for
paths:
• –LiteralPath treats all characters as literals, and does not interpret any characters as a wildcard. The
literal path *.txt means “the item named *.txt.” This approach is useful in drives where * and ? are
allowed in item names, such as in the registry.
In the drive HKCU, items are registry keys. These registry keys can contain other keys, and can have their
own item properties. For example, HKCU:\Volatile Environment has item properties named
LOGONSERVER, USERDOMAIN, HOMEPATH, and so on. That key also contains other registry keys that
have their own item properties. Use Get-ItemProperty and Set-ItemProperty to work with item
properties.
Demonstration Steps
1. Change to the C:\ location.
Question: If Get-Content displays the contents of a text file on the file system, how could
you display the contents of a built-in function like Help?
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 04-9
Objectives
After completing this lab, students will be able to:
Lab Setup
Estimated Time: 30 minutes
Virtual Machines: 10961A-LON-DC1, 10961A-LON-CL1
Password: Pa$$w0rd
The changes that you make during this lab will be lost if you revert your virtual machines at another time
during class.
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must
follow these steps:
1. On the host computer, move the pointer over the bottom left corner of the taskbar, click Start, and
then click Hyper-V Manager on the Start screen.
2. In Hyper-V® Manager, click 10961A-LON-DC1, and in the Actions pane, click Start.
3. In the Actions pane, click Connect. Wait until the virtual machine starts.
o Password: Pa$$w0rd
o Domain: ADATUM
6. The exercise steps should be performed using the 10961A-LON-CL1 virtual machine throughout this
lab.
Results: After completing this exercise, you will have created a new folder on the file system.
2. Create a new PSDrive named Output: and map it to the C:\ScriptOutput folder.
Results: After completing this exercise, you will have created a new, temporary PSDrive.
Results: After completing this exercise, you will have created a new registry key.
o Value: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Results: After completing this exercise, you will have added a new program to the autorun list.
Results: After completing this exercise, you will have modified the maximum number of concurrent
connections for Windows PowerShell remoting.
Question: Of the PSProviders included with Windows PowerShell, which support the use of
alternative credentials?
Question: Windows PowerShell 3.0 can make one kind of PSDrive visible in File Explorer.
What kind of drive is that, and how do you make it visible?
MCT USE ONLY. STUDENT USE PROHIBITED
04-12 Using PSProviders and PSDrives
Review Question(s)
Question: What is the advantage of managing something by using a PSProvider instead of
commands?
Module05
Formatting Output
Contents:
Module Overview 05-1
Module Overview
In this module, you will learn how to format the output of commands. Formatting enables you to produce
more professional-looking output, and to produce output that is better customized for your specific
needs.
Additional Reading: This module mentions the ability to create custom formatting views
in Windows PowerShell™. You can read more about that ability at
http://technet.microsoft.com/en-us/library/hh847831.aspx.
Additional Reading: Although you can create simple management reports by using
Windows PowerShell™ formatting, more complex reports can be created by using Microsoft® SQL
Server® Reporting Services (SSRS). For more information, read “Making Historical and Trend
Reports in Windows PowerShell,” a free paper available at http://www.PowerShellBooks.com.
Objectives
After completing this module, students will be able to:
Lesson 1
Using Basic Formatting
In this lesson, you will learn about the three basic formatting commands in Windows PowerShell.
Lesson Objectives
After completing this lesson, students will be able to:
Default Formatting
To this point, all the commands that you have run
in Windows PowerShell have used the shell’s
default formatting system to produce their results
on the screen. This formatting system uses the
following rules:
3. If the object type does not have a defined view, decide whether the object type has a default display
property set. If it does, the properties in that set will be displayed. If there are five or more properties,
they will be displayed as a list. Otherwise, they will be displayed as a table.
4. If the object type does not have a default display property set, all the properties will be displayed. If
there are more than four properties, they will be displayed as a list. Otherwise, they will be displayed
as a table.
You can define your own views and property sets to change the default appearance of a specified object
type. Doing this is beyond the scope of this course. However, you can read the Help for Update-
FormatData and Update-TypeData for more information.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 05-3
Wide Lists
You can pipe objects to the Format-Wide
command to produce a wide list. The command
defaults to a two-column display of the objects’
Name properties (because most objects have a
Name property). The command has the alias FW.
Lists
You can pipe objects to the Format-List
command to display objects’ properties in a list
format. If you do not specify properties to display,
and the object has a set that is defined, the
objects’ default display property set will be shown.
Otherwise, all the objects’ properties will be
shown. Format-List has the alias FL.
Format-List does not contain other parameters that you will use frequently. Read the Help for the
command to learn about its other parameters.
Tables
You can pipe objects to the Format-Table
command to display object properties in a
columnar format. Format-Table has the alias FT.
separated list of property names. You can use the wildcard * to display all properties. However, for
objects having lots of properties, the command may eliminate columns that do not fit.
• The –AutoSize parameter tries to size each column to hold its widest item, and eliminates additional
space between columns.
• The –Wrap parameter enables column content to wrap across several lines. This prevents data from
being truncated.
Demonstration Steps
1. Display a list of process ID numbers in a two-column wide list.
2. Display a list of process ID numbers in a five-column wide list.
3. Display a list of process names in as many columns as will fit on the screen.
6. Display a table that shows the most recent 50 entries from the Security event log. Display only the
time written and event ID for each entry. Do not allow additional space between table columns.
Question: Look at the full Help for one of the format commands. What parameter do they
all use to accept input from the pipeline?
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 05-5
Lesson 2
Using Advanced Formatting
In this lesson, you will learn to use some of Windows PowerShell’s advanced formatting options and
techniques.
Lesson Objectives
After completing this lesson, students will be able to:
For example:
Get-Process |
Format-Table -Property Name,ID,@{n='VM(MB)';
e={$PSItem.VM / 1MB};
formatString='N2';
align='right'} -AutoSize
Name Id VM(MB)
---- -- ------
conhost 3948 59.28
csrss 584 48.38
csrss 648 48.27
dllhost 2084 55.21
dwm 964 375.39
MCT USE ONLY. STUDENT USE PROHIBITED
05-6 Formatting Output
Demonstration Steps
1. Display a list of local hard disks that includes free space in gigabytes, size in gigabytes, and
description. Limit the description to five characters and do not include additional space between
columns.
2. Display the same list again, but allow additional space between columns.
Demonstration Steps
1. Display a list of services, grouped by status. Do not sort the objects.
Select or Format?
There is overlapping functionality between the
Select-Object command and the formatting
commands. Both accept a property list that
controls the properties displayed. Both can accept
custom, or calculated, properties.
You will learn more about the differences between formatting commands and Select-Object in the next
lesson.
Question: What custom column keys are allowed in Format-Table that are not allowed in
the calculated properties of Select-Object?
MCT USE ONLY. STUDENT USE PROHIBITED
05-8 Formatting Output
Lesson 3
Redirecting Formatted Output
In this lesson, you will learn how to redirect formatted output to locations other than the screen. You will
also learn about the rules for redirection, and how to display data in other forms.
Lesson Objectives
After completing this lesson, students will be able to:
Get-Process |
Format-Table –Property Name,ID,VM,PM –AutoSize |
ConvertTo-HTML |
Out-File C:\Processes.html
The intent is to produce an HTML table. However, this command produces unusable output because
ConvertTo-HTML cannot receive the output of a format command.
Demonstration Steps
1. Use Get-Member to examine the output of Get-Process.
These commands can all follow a format command on the pipeline. For example:
Get-Process |
Format-Table –Property Name,ID,@{n='VM';e={$PSItem.VM / 1KB};formatString='N2'} |
Out-File Procs.txt
The content of the file or printed page will look exactly as it would have on the screen. These commands
do not convert data to another format like CSV or XML. These commands merely take output that usually
would have appeared on the screen, and redirect it to a file or printer.
Demonstration Steps
1. Run the following command and let the output appear on the screen:
Get-Process |
Format-Table –Property Name,ID,@{n='VM';e={$PSItem.VM / 1KB};formatString='N2'}
2. Run the same command again, but redirect the output to a file that is named C:\Procs.txt.
Demonstration Steps
1. Display all running processes in a grid view.
Objectives
After completing this lab, students will be able to:
Lab Setup
Estimated Time: 45 minutes
Password: Pa$$w0rd
The changes that you make during this lab will be lost if you revert your virtual machines at another time
during class.
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must
follow these steps:
1. On the host computer, move the pointer over the bottom left corner of the taskbar, click Start, and
then click Hyper-V Manager on the Start screen.
2. In Hyper-V® Manager, click 10961A-LON-DC1, and in the Actions pane, click Start.
3. In the Actions pane, click Connect. Wait until the virtual machine starts.
o Password: Pa$$w0rd
o Domain: ADATUM
o Computer name
o Description
o Domain
o Manufacturer
o Model
o Number of processors
o ID
The table should not have additional space between the columns. Redirect the table to a text file that
is named Procs.txt.
o Route metric
o Type of route
o Destination prefix
Destination prefix must be right-aligned. The table must not include additional space between
columns.
Results: After completing this exercise, you will have created various commands that produce formatted
output.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 05-13
Task 1: Write a command that displays file names and sizes as specified
• Write a command that will display a list of all files having an .exe file name extension in the
C:\Windows directory. Your output must look exactly as follows:
Name Size(KB)
---- --------
explorer.exe 2,324.65
HelpPane.exe 863.00
notepad.exe 238.00
regedit.exe 155.50
splwow64.exe 123.50
bfsvc.exe 73.50
hh.exe 17.00
winhlp32.exe 10.50
write.exe 10.50
2. Display the most recent 20 entries from the Security event log. Calculate the difference between the
time each event was generated and the time that it was written. Display the list exactly as shown here,
with the largest time difference shown first, and the smallest time difference shown last.
EventID TimeDifference
------- --------------
4672 00:00:02
4624 00:00:01
4672 00:00:00
4624 00:00:00
4672 00:00:00
4624 00:00:00
2. In the Virtual Machines list, right click 10961A-LON-DC1, and then click Revert.
Results: After completing this exercise, you will have written commands to reproduce specified output.
Question: If you redirected formatted output to a file, is there a command that would let
you attach that file to an email message?
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 05-15
Always make sure that your command works correctly before you worry about how to format the
output. Formatting can be complex, and doing it last will help you avoid many common
mistakes.
Review Question(s)
Question: Where might you use Out-GridView?
Module06
Querying Management Information by Using WMI and CIM
Contents:
Module Overview 06-1
Module Overview
In this module, you will learn about two parallel technologies. Windows® Management Instrumentation
(WMI) and Common Information Model (CIM) both provide local and remote access to a repository of
management information including access to robust information available from the operating system,
computer hardware, and installed software.
Objectives
After completing this module, students will be able to:
Lesson 1
Understanding WMI and CIM
In this lesson, you will learn about the architecture of both WMI and CIM. You will learn about the
differences between the two technologies, and learn to select the appropriate technology for a given
scenario.
Lesson Objectives
After completing this lesson, students will be able to:
Both technologies provide a way to connect to a common information repository (also known as the WMI
repository). This repository holds management information that you can query and manipulate. Windows
PowerShell™ 3.0 supports both technologies. Earlier versions of Windows PowerShell support only WMI. In
Windows PowerShell 3.0, two parallel sets of commands let you perform tasks by using either WMI or
CIM.
Reference Links: The Distributed Management Task Force (DMTF) website is available
here http://www.dmtf.org.
CIM Commands
CIM commands provide many different cross-platform and cross-version capabilities. They support three
kinds of connections:
• Ad hoc connections to a remote computer, which always use the Web Services for Management (WS-
MAN) protocol. This protocol is based on HTTP.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 06-3
• Session-based connections to a remote computer, which can use either DCOM or WS-MAN.
DCOM connections are typically made to the Windows Management Instrumentation (WMI) service that
is part of the Windows operating system. WS-MAN connections are made to the Windows Remote
Management (WinRM) service, which is the same service that enables Windows PowerShell remoting. You
will learn more about remoting in Module 9, “Administering Remote Computers.” WinRM is part of the
Windows Management Framework, and is included in Windows Management Framework 2.0 and newer
versions. WinRM is installed by default on computers that are running Windows 7, Windows 8, Windows
Server® 2008 R2, and Windows Server 2012. Although installed by default on all those operating systems,
WinRM and remoting are enabled by default only on Windows 8 and Windows Server 2012.
You can use CIM commands in two ways. The first requires the remote computer to have WinRM installed
and enabled. That will typically require that Windows Management Framework 3.0 be installed and that
Windows PowerShell remoting be enabled. The second way to use CIM commands is to tell the command
to use the earlier WMI technology. That is the same technology used by the WMI commands, and it does
not require that Windows Management Framework be installed on the remote computer.
WMI Commands
WMI commands use the same repository as CIM commands. The only difference is in how the WMI
commands connect to a remote computer.
WMI commands do not support session-based connections. The commands support only ad hoc
connections over DCOM. Whether used by WMI or CIM commands, DCOM can be difficult to use on
some networks. DCOM uses the remote procedure call (RPC) protocol. That protocol requires special
firewall exceptions to work correctly.
WMI commands communicate with the WMI service. They do not require any version of the Windows
Management Framework on a remote computer, and they do not require that Windows PowerShell
remoting be enabled. If the remote computer has the Windows Firewall feature enabled, WMI commands
require that the Remote Administration exception be enabled on the remote computer. If the remote
computer has a different local firewall enabled, an equivalent exception must be created and enabled.
Because CIM commands can also use DCOM, WMI commands are typically necessary only when you have
to make an ad hoc connection to a computer that does not have Windows PowerShell remoting enabled.
• CIM cmdlets can use DCOM or WS-MAN for session-based connections to remote computers
The WMI cmdlets can be used when you must make an ad hoc connection to a computer that does not
have Windows Management Framework 2.0 or a newer version installed, or to a computer that has
Windows Management Framework 2.0 installed but that does not have Windows PowerShell remoting
enabled. However, the CIM cmdlets can connect to a computer that does not have Windows
Management Framework 2.0 or a newer version installed, and to computers that do not have Windows
PowerShell remoting enabled. You must use a CimSession to connect to those computers. You will learn
about CIM sessions in the next lesson.
commands. You should rely primarily on CIM commands, and use WMI commands only when
CIM commands are not practical.
In Windows 8 and Windows Server 2012, Microsoft introduced hundreds of new commands in Windows
PowerShell. Many of these commands internally use WMI or CIM. These commands provide better access
to the functionality of WMI and CIM so that you can use that functionality without having to deal with
their complexity.
The Repository
The repository used by CIM and WMI is organized
into namespaces. A namespace is basically a
folder, and is used to group related items for
organizational purposes.
When you work with the repository, you typically work with instances. An instance represents an actual
occurrence of a class. For example, if your computer has two processor sockets, you will have two
instances of the class that represents processors. If your computer does not have an attached tape drive,
you will have zero instances of the tape drive class.
Instances are objects, similar to the objects that you have already used in Windows PowerShell. Instances
have properties, and some instances have methods. Properties describe the attributes of an instance. For
example, a network adapter instance might have properties that describe its speed, its power state, and so
on. Methods tell an instance to do something. For example, the instance that represents the operating
system might have a method to restart the operating system.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 06-5
Finding Documentation
Class documentation can be difficult to find.
Although many Microsoft product groups and
independent software vendors (ISVs) expose
management information in the repository, few of
them create formal documentation. In most cases,
an Internet search for a class name will be your
best option for finding whatever documentation
exists.
Remember that both WMI and CIM are not a native part of Windows PowerShell. Instead, they are
external technologies that Windows PowerShell can use and understand. However, because they are
external technologies, the repository classes are not documented in Windows PowerShell’s native Help
system.
Demonstration Steps
• Locate the online documentation for the Win32_BIOS class.
Question: Can you think of any situations where you would have to use WMI instead of
CIM?
MCT USE ONLY. STUDENT USE PROHIBITED
06-6 Querying Management Information by Using WMI and CIM
Lesson 2
Querying Data by Using WMI and CIM
In this lesson, you will use both WMI and CIM commands to query the repository.
Lesson Objectives
After completing this lesson, students will be able to:
Listing Namespaces
You can use Windows PowerShell to list all the
namespaces on the local computer or on a remote
computer. Run this command:
Demonstration Steps
• Use WMI to list all local namespaces.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 06-7
Listing Classes
Windows PowerShell can list all the classes in a
particular namespace. For example, to list all the
classes in the root\CIMv2 namespace, run either
of these commands:
Windows PowerShell supports tab completion of namespace names for CIM commands only. You can
type Get-Cim[tab] –Nam[tab] roo[tab] to quickly type the second command, pressing the Tab key
where [tab] is shown.
Classes are not listed in any particular order. Finding a class can be easier when they are listed
alphabetically. For example, if you are looking for a class that represents a process, but do not know the
class name, you could quickly move to the “P” section of a sorted list and start to look for the word
process. To produce an alphabetical list of classes in the root\CIMv2 namespace, run either of these
commands:
Note: In the root\CIMv2 namespace you will see classes whose names start with Win32_
and other classes whose names start with CIM_. This namespace is the only one where those
prefixes are used. Classes starting with CIM_ are typically abstract classes. Classes starting with
Win32_ are typically more specific versions of the abstract classes, and contain information that is
specific to the Windows operating system.
Many administrators feel that the repository can be difficult to work with. Finding the class that you must
have to perform a given task is basically a guessing game. You have to guess at what the class might be
named, and then look through the class list to determine whether you were right. Then you must query
the class to determine whether the class contains the information that you need. Because many classes
outside the root\CIMv2 namespace are not well-documented, this is your best approach. An
administrator who is good at using WMI and CIM is also good at making educated guesses.
There is no central directory of repository classes. The repository does not include a search system. You
can use Windows PowerShell to perform a basic keyword search of repository class names. For example,
to find all classes in the root\CIMv2 namespace having network in the class name, use this:
However, this technique cannot search class descriptions, because that information is not stored in the
repository. Frequently, an Internet search engine will provide a better way to search for possible class
names.
MCT USE ONLY. STUDENT USE PROHIBITED
06-8 Querying Management Information by Using WMI and CIM
Note: You may see some classes whose names begin with two underscore characters (__).
These are system classes and they are used internally by WMI and CIM.
Reference Links: A graphical WMI Explorer tool, written in Windows PowerShell script, is
available from http://www.PowerShell.org/wp/2013/03/08/wmi-explorer/. This tool can make it
easier to explore the WMI classes that are available on a given computer.
Demonstration Steps
1. List the classes in the root\SecurityCenter2 namespace.
2. List the classes in the root\CIMv2 namespace. Sort the list by name.
Querying Instances
When you know what class you want to query,
Windows PowerShell can retrieve class instances
for you. For example, if you wanted to retrieve all
instances of the Win32_LogicalDisk class from
the root\CIMv2 namespace, you could run either
of the following commands:
Both the –Class parameter of Get-WmiObject, and the –ClassName parameter of Get-CimInstance, are
positional. That means the following commands work the same way:
Get-WmiObject Win32_LogicalDisk
Get-CimInstance Win32_LogicalDisk
By default, both commands retrieve all available instances of the specified class. You can specify filter
criteria to retrieve a smaller set of instances. The filter languages used by these commands do not use
Windows PowerShell comparison operators. Instead, traditional programming operators are used, as
shown in the following table.
Windows PowerShell
Comparison WMI and CIM operator
operator
Equality = -eq
Windows PowerShell
Comparison WMI and CIM operator
operator
Boolean OR OR -or
For example, to retrieve only the instances of Win32_LogicalDisk, where the DriveType property is 3,
run either of the following commands:
Note: WMI and CIM require that string values within the filter criteria be contained within
single quotation marks. For example, Name='BITS'. For this reason, the whole filter value must
be contained within double quotation marks. Using double quotation marks for the entire filter
value ensures that the enclosed single quotation marks are correctly sent to WMI or CIM. Date
values are also enclosed within single quotation marks.
Note: Many class properties use integers to represent different kinds of things. For
example, in the Win32_LogicalDisk class, the DriveType property of 3 represents a local fixed
disk. A 5 represents an optical disk, such as a DVD drive. You will have to examine the class
documentation to learn what each value represents.
This command syntax makes it easier to reuse existing query statements that you may have, or that you
may find in examples written by other people. A detailed examination of WQL is beyond the scope of this
course, and you will not cover it further in this course.
Demonstration Steps
1. Use WMI to display all instances of the Win32_Service class.
3. Use CIM to display those instances of the Win32_LogicalDisk class having a drive type of 3.
4. Use CIM and a WQL query to display all instances of the Win32_NetworkAdapter class.
Remote Computers
At this point in this lesson, you have queried only
the local computer’s repository. Both the WMI
and CIM commands are able to connect to a
remote computer. When they connect to a
remote computer, they can also specify alternative
credentials for the connection.
If you specify multiple computer names, Windows PowerShell will contact them one at a time in the order
that you specify. If one computer fails, the command produces an error message and continues to try the
remaining computers.
The CIM commands also support a –ComputerName parameter and a –Credential parameter. Using
these creates an ad hoc connection. If you plan to query multiple classes from the same computer, you
can achieve better performance by creating a persistent CIM session instead.
Remember that the CIM commands use the WS-MAN protocol for ad hoc connections. This protocol has
specific authentication requirements. Between computers in the same domain or in trusting domains, you
typically have to provide a computer’s name as it appears in Active Directory®. You cannot typically
provide an alias name or an IP address. You will learn more about these and other restrictions in Module
9, “Managing Remote Computers.” You will also learn how to work around these restrictions.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 06-11
Using CIMSessions
A CIM session is a persistent connection to a
remote computer, made by using the WS-MAN or
DCOM protocol. After a session is created, you
can use it to process multiple queries for that
computer. You will achieve better performance
across multiple queries by using a session rather
than by using multiple ad hoc connections.
When you have one or more sessions in a variable, you can send CIM queries to those sessions:
Remember that sessions are designed to work best in a domain environment, between computers in the
same domain or in trusting domains. If you have to create a session to a non-domain computer, or to a
computer in a non-trusted domain, additional configuration is required. You will learn more about those
requirements in Module 9, “Managing Remote Computers.”
A session option enables you to specify many session options. One option lets you create the session by
using DCOM instead of WS-MAN:
The first line in the preceding code defines the CIM DCOM session option. The second line defines the
session variable using that CIM DCOM session option, and the final line returns data from the remote
machine using that defined session.
CIM sessions remain open while being used. A system-wide idle time-out will close an unused session
after the specified time. You can also manually close the sessions for a specified remote computer:
$sess | Remove-CimSession
Get-CimSession | Remove-CimSession
Note: The Help for some commands, such as Get-SmbShare, state that they support a –
CimSession parameter. Those commands use CIM internally. When using those commands to
query a remote computer, you can provide a CIM session object to the –CimSession parameter
to connect by means of the existing session.
MCT USE ONLY. STUDENT USE PROHIBITED
06-12 Querying Management Information by Using WMI and CIM
Demonstration Steps
1. Create CIM sessions to LON-CL1 and LON-DC1. Store both sessions in a variable.
2. Using the variable, query the Win32_OperatingSystem class from LON-CL1 and LON-DC1.
Lesson 3
Making Changes by Using WMI and CIM
In this lesson, you will learn to use WMI and CIM to make changes by executing methods.
Lesson Objectives
After completing this lesson, students will be able to:
Discovering Methods
You have learned that objects contain members,
and that those members consist of properties,
methods, and events. To this point in this course,
you have used properties of objects. Now you will
be able to use methods.
If you know the class that represents the manageable component that you want to reconfigure, you can
discover the methods of that class by using Get-Member:
The resulting list will display all available methods. Remember that not every class offers methods, so
sometimes the list may not include any methods. The output of Get-Member does not explain how to
use the methods; unless you already know how to use them, you have to find the documentation for the
class.
The same technique will not work with Get-CimInstance, because the objects returned by that command
do not have a complete set of methods. Instead, you would run this command:
There is no efficient way to search across all classes for a given method. To do this in Windows PowerShell,
you would have to query every class, pipe each one to Get-Member, and search that output for a
method name or keyword. This approach would be very time-consuming and impractical. An Internet
search engine would provide a faster and easier way to search for classes and methods.
MCT USE ONLY. STUDENT USE PROHIBITED
06-14 Querying Management Information by Using WMI and CIM
The main use of the documentation is to determine what arguments each method requires. For example,
the Win32Shutdown() method of the Win32_OperatingSystem class accepts a single argument. The
argument is an integer, and it tells the method what kind of shut down, restart, or other action to take.
Demonstration Steps
1. Display the members of the Win32_Service class.
2. Use Windows PowerShell to display the definition for the Change() method of Win32_Service.
Invoking Methods
When you know the method that you want to use,
and you know how to use it, you can invoke the
method. There are three ways to invoke a method.
Invoke-WmiMethod
The Invoke-WmiMethod command can be used
by itself, or it can accept a WMI object from Get-
WmiObject by using the pipeline. Here are two
examples that will work the same:
Get-WmiObject –Class
Win32_OperatingSystem |
Invoke-WmiMethod –Name Win32Shutdown –
Argument 0
Invoke-WmiMethod –Class Win32_OperatingSystem –Name Win32Shutdown –Argument 0
Both Get-WmiObject and Invoke-Method have a –ComputerName parameter that lets you run the
method on a remote computer.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 06-15
Invoke-WmiMethod will not work correctly if the argument list has to contain a NULL value. For
example, the Change() method of the Win32_Service class accepts several different arguments. You can
provide NULL as a value for any argument that you do not want to change. For example, if you want to
change only the service’s logon password, you provide NULL for the first seven arguments, and a new
password for the eighth argument. Invoke-WmiMethod does not support the use of those NULL values.
Invoke-WmiMethod is a WMI command. That means that it communicated by using the DCOM
protocol.
Invoke-CimMethod
The Invoke-CimMethod command resembles Invoke-WmiMethod. However, because it is a CIM
command, it communicates by using different protocols:
• When you use an established CIMSession, it uses either DCOM or WS-MAN, depending on how the
session was created.
The argument list for Invoke-CimMethod is a dictionary object. These objects consist of one or more
key-value pairs. The key for each pair is the argument name, and the value for each pair is the
corresponding argument value. For example:
To include multiple arguments in the dictionary, use a semicolon (;) to separate each key/value pair. The
command can also accept a repository object from Get-CimInstance:
Notice that you do not have to specify the –Arguments parameter for methods that do not require any
arguments.
If you use –ComputerName or –CIMSession with Get-CimInstance, and pipe the resulting object to
Invoke-CimMethod, Invoke-CimMethod will invoke the method on whatever computer or session the
object came from. For example, to terminate a process on a remote computer:
ForEach-Object
If Invoke-WmiMethod and Invoke-CimMethod cannot be used, you can retrieve repository objects and
enumerate them to execute methods. For example:
This example changes the logon password of the service named MyService. When you use this technique
to invoke a method, you must follow these rules:
• The method name must be followed by an open parenthesis. You may not include a space between
the method name and the parentheses.
• Parentheses are required even if the method does not accept any arguments.
• Windows PowerShell uses the built-in variable $null to represent the value NULL.
Demonstration Steps
1. Using CIM and the Reboot() method of Win32_OperatingSystem, restart LON-DC1.
3. Using WMI and the Terminate() method of Win32_Process, close Windows Paint.
Question: What are some disadvantages of using ForEach-Object instead of one of the
Invoke commands to invoke a method?
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 06-17
Objectives
After completing this lab, students will be able to:
Lab Setup
Estimated Time: 45 minutes
Password: Pa$$w0rd
The changes that you make during this lab will be lost if you revert your virtual machines at another time
during class.
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must
follow these steps:
1. On the host computer, move the pointer over the bottom left corner of the taskbar, click Start, and
then click Hyper-V Manager on the Start screen.
2. In Hyper-V® Manager, click 10961A-LON-DC1, and in the Actions pane, click Start.
3. In the Actions pane, click Connect. Wait until the virtual machine starts.
b. Password: Pa$$w0rd
c. Domain: ADATUM
2. Using a WMI command and the class that you discovered in the previous step, display a list of all IP
addresses received by using DHCP.
2. Display a list of properties for the class that you discovered in the previous step.
3. Write the properties that contain the operating system version, service pack major version, and
operating system build number.
4. Using a WMI command and the class that you discovered in step 1, display the local operating system
version, build number, and service pack major version.
2. Display a list of properties and property values for the class that you discovered in the previous step.
3. Using the list of properties and a WMI command, display the local computer’s manufacturer, model,
and total physical memory. Label the column for total physical memory as RAM.
3. Using the list of properties and a WMI command, display the service name, status (running or
stopped), and logon name for all services whose names start with S.
Results: After completing this lab, you will have queried repository classes by using WMI commands.
2. Using a CIM command, display a list of properties for the class that you discovered in the previous
step.
3. Using a CIM command and the property list, display a list of user accounts in a table. Include columns
for the account caption, domain, SID, full name, and name. The full name column may be blank for
some or all accounts.
2. Using a CIM command and the class that you discovered in the previous step, display a list of all
available BIOS information.
Results: After completing this exercise, you will have queried repository classes by using CIM commands.
2. In the Virtual Machines list, right click 10961A-LON-DC1, and then click Revert.
MCT USE ONLY. STUDENT USE PROHIBITED
06-20 Querying Management Information by Using WMI and CIM
Results: After completing this exercise, you will have used CIM and WMI commands to invoke methods of
repository objects.
Question: One of your lab tasks directed you to query Win32_Product. Do you know of any
disadvantages when you use this class?
Question: What are the main differences between WMI and CIM?
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 06-21
Use CIM commands when possible. Unlike WMI commands, the CIM commands offer better
performance and are the commands that Microsoft continues to develop and improve over time.
Review Question(s)
Question: What do you think is the most difficult part about working with WMI and CIM?
Tools
Another way to explore the repository is to use a graphical tool. One tool is the PowerShell
Scriptomatic, available at http://technet.microsoft.com/en-us/library/ff730935.aspx.
MCT USE ONLY. STUDENT USE PROHIBITED
06-22 Querying Management Information by Using WMI and CIM
MCT USE ONLY. STUDENT USE PROHIBITED
07-1
Module07
Preparing for Scripting
Contents:
Module Overview 07-1
Module Overview
In this module, you will prepare yourself and Windows PowerShell™ to write and run scripts. Although you
may have used variables in previous modules of this course, you will now learn about their rules and
correct use. You will also learn about the shell’s built-in security measures for scripts.
Additional Reading: You can read more about Windows PowerShell scripting, and find an
online community script repository, at http://technet.microsoft.com/en-
us/scriptcenter/powershell.aspx.
Objectives
After completing this module, students will be able to:
• Create, use, and manage variables
Lesson 1
Using Variables
Previous modules in this course introduced variables as a temporary storage container for objects. In this lesson,
you will learn more about variables and all the rules for using them.
Lesson Objectives
After completing this lesson, students will be able to:
The shell stores variables in the PSDrive VARIABLE:. You can use that drive to change variables, view
them, and remove them. The shell also provides a set of commands that manage variables. To see a list,
run Get-Command –Noun Variable. Most Windows PowerShell users do not use those commands,
because the shell also supports ad hoc variable creation and management. You will see the ad hoc
technique in this lesson.
Every time that you start a new Windows PowerShell session, it has its own drive VARIABLE:. That drive is
populated with several built-in variables that control different parts of the shell’s behavior. Some of those
built-in variables are constants, meaning they are read-only and cannot be changed. For example, the
built-in $ShellId variable is read-only. The built-in $VerbosePreference is not read-only, and can be
changed.
Variables are scoped. That means that they can be created inside a specific in-memory container, and they
exist only as long as their container exists. Variables created at the command prompt are stored in the
global scope, and exist only until the current shell session is closed. Variables created in a script exist only
until that script finishes running. Variables created inside a function exist only until that function finishes
running.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 07-3
Variable Rules
Variables must have a name. Typically, names
consist of letters, numbers, and underscores.
However, you can also create variable names that
contain other characters if you use a special
syntax. The following are all examples of enabled
variable names:
• X
• ComputerName
• Count5
• Modified_Amount
• {Server Path}
The last example, {Server Path}, is a variable name that contains a character (that is, a space) that would
not typically be enabled in a variable name. By enclosing the variable name in curly braces, you can use
any character except curly braces. Variable names such as {Server Path} are more difficult to type and to
read, and are not recommended.
Best Practice: As a best practice, use variable names that contain only letters and numbers.
Use underscores only when necessary. Avoid creating variable names that use curly braces {} to
enclose a name that contains spaces or other characters.
You will typically see variable names preceded by a dollar sign ($). The dollar sign is not part of the
variable name. The dollar sign tells Windows PowerShell that you want to access the contents of the
variable, instead of working with the variable itself. For example:
$var = 'daily'
Set-Variable –Name $var –Value 700
In this example, the shell will set the variable daily to the value 700. The value of $var remains “daily”
after the second command is run.
This behavior typically confuses beginning users, who expect the shell to set var to 700. The dollar sign
tells the shell to access the contents of var, which is daily. The –Name parameter therefore receives daily,
and so that is the variable it sets.
MCT USE ONLY. STUDENT USE PROHIBITED
07-4 Preparing for Scripting
Using Variables
Using variables is straightforward. To assign
objects to a variable, use the = assignment
operator. Remember that the equal sign in
Windows PowerShell is not a comparison operator
for equality. That operator is –eq. The equal sign is
used only for assignment. Whatever appears on
the right side of the equal sign is executed, and its
result will be stored in whatever is located on the
left side of the equal sign:
Note: You can run Get-Variable, or run Dir VARIABLE:, to list all variables. The Clear-
Variable command will remove a variable’s value, and you can use the Remove-Item command
in the VARIABLE: drive to delete a variable.
Using Arrays
A variable that contains more than one object is an array. In the previous example, $services is an array.
To access individual objects in an array, use an index number in square brackets. For example:
PS C:\> $services = Get-Service | Where Status –eq 'Running' | Sort Name –Descending
PS C:\> # First object in the array
PS C:\> $services[0]
Status Name DisplayName
------ ---- -----------
Running WSearch Windows Search
PS C:\> # Second object
PS C:\> $services[1]
Status Name DisplayName
------ ---- -----------
Running wscsvc Security Center
PS C:\> # Last object
PS C:\> $services[-1]
Status Name DisplayName
------ ---- -----------
Running Appinfo Application Information
PS C:\> # Just the name of the third object
PS C:\> $services[2].Name
WinRM
PS C:\> # Just the status of the second-to-last object
PS C:\> $services[-2].Status
Running
Accessing Members
Almost everything in Windows PowerShell is an object, and objects have members. Members can include
methods and properties. When a variable contains an object, accessing just the variable returns the whole
object:
You can use the member resolution operator, which is a period, to access individual members of an
object:
PS C:\> $today.DayOfWeek
Thursday
PS C:\> $today.AddDays(90)
Wednesday, April 10, 2013 8:33:16 AM
PS C:\> $x = Get-Service
PS C:\> $x = Get-Process
Those two commands will run without error. After the first command, X contains a collection of
System.ServiceProcess.ServiceController objects. After the second command, X changes to contain a
collection of System.Diagnostics.Process objects.
You can specify a type for variables. When you do this, the shell will not let objects of another type be
stored in the variable. Common types include the following:
For example:
This example shows an error, because the variable X can no longer contain a String object. It can contain
only integers, and the string Hello could not be converted to an integer. You can explicitly retype a
variable:
You can also use the –is operator to determine whether a variable contains objects of a specified type,
and the –as operator to convert an object to a different type. For example:
That example shows both the –is and –as operators. You will learn more about these in Module 12,
MCT USE ONLY. STUDENT USE PROHIBITED
07-6 Preparing for Scripting
Common Mistakes
Windows PowerShell beginning users will frequently forget that an object is a complex data structure that
consist of many members. For example, the following is a common mistake:
• $file does not necessarily contain only one object. It may contain multiple objects, that is, if there are
multiple files present. Get-Content can retrieve the content from multiple files at the same time, but
that may not be the intended result.
• $file contains all of a FileInfo object, but the –Path parameter of Get-Content accepts only a String
object.
This revised example would work correctly in Windows PowerShell 3.0. The variable file actually contains a
collection of objects, and the collection does not have a FullName property. In earlier versions of
Windows PowerShell, this example would fail. In Windows PowerShell 3.0, the example works because the
shell assumes that you intended to access the FullName property of each object in the collection, instead
of the collection itself.
• - for subtraction
• * for multiplication
• / for division
PS C:\> $x = 5
PS C:\> $y = 5
PS C:\> $x + $y
10
PS C:\> $x * $y
25
Variables in Strings
When a string is enclosed in single quotation marks, Windows PowerShell does not evaluate the contents
of the string. For example:
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 07-7
However, when the string is enclosed in double quotation marks, the shell looks for the dollar sign
character. When it finds one, it assumes that the following characters are a variable name, and it replaces
the variable with its contents. For example:
Note: Windows PowerShell also evaluates the grave accent (‘) in double quotation marks.
When the grave accent is placed before any other character, the grave accent will remove that
character’s special meaning, if it has one. For example, `$x will be treated as the literal value $x
because the grave accent removes the special meaning of $. For some characters, including t and
n, the grave accent assigns special meaning. For example, `t represents a tab character, and `n
represents a new line character.
For more details about grave accents, see help about_escape_characters.
Subexpressions in Strings
Variable replacement works only for the variable itself. You cannot access a member of a variable by using
that same syntax. For example:
In this example, $process was replaced. When Windows PowerShell 3.0 is asked to display a collection of
objects, it displays their name so that the results show the name of every process. Notice that the end of
the results includes [0].name. That portion of the code was not used as part of the replacement. This
example shows a common mistake made by beginning users. The correct way to perform this task is to
use a subexpression:
The subexpression consists of $(). Everything inside the parentheses is treated as executable code, and the
subexpression is replaced with the result of that executable code.
MCT USE ONLY. STUDENT USE PROHIBITED
07-8 Preparing for Scripting
Best Practice: By using variables, subexpressions, and double quotation marks, you should
never have to use + as a string concatenation operator. For example, instead of $result = "The
first service is named " + $services[0].name, you should use $result = "The first service is
named $($services[0].name)". Subexpressions enclosed in double quotation marks are typically
easier to read than concatenated string expressions.
Demonstration Steps
1. Assign 100 to the variable x1.
3. Use the variable procs to display the name of the first running process.
4. Use the variable procs to display a list of processes, sorted in descending order of virtual memory use.
5. Using double quotation marks and the variable x1, display the phrase The content of x1 is 100.
7. Using the variables x1 and x2, display the result of 100 multiplied by 100.
8. Using the variable procs and double quotation marks, display the name and CPU usage of the first
running process.
9. Using the variable x2, double quotation marks, and the grave accent, display the phrase $x2
contains 100.
10. Using the variable procs, display the name of all running processes.
11. Using the variable procs, display all properties and property values for the first running process.
Lesson 2
Scripting Security
In this lesson, you will learn about Windows PowerShell’s features for scripting security. You will also learn
about the shell’s security goals.
Lesson Objectives
After completing this lesson, students will be able to:
Security Goals
Before you start to explore Windows PowerShell’s
security features, you should understand the
shell’s objectives and goals for security.
Thus, the scope of the shell’s security features is very specific. The shell does not eliminate the need for
antimalware software. The shell does not reduce the need for good security practices and configurations.
The shell does not eliminate the need to educate users about good security practices. The shell’s security
features are intended to be part of a multilayer security strategy, following the principle of defense in
depth.
One example of what the shell’s security features protect against are the many different viruses that were
based on Microsoft® Visual Basic® Scripting Edition (VBScript) in the early 1990s. Those viruses were
typically spread through emails. For example, a script named “Postcard from your Mother.vbs” would be
included as an email attachment. Unsuspecting users would open the script expecting a message from a
parent, and instead the script would execute. Windows PowerShell’s features are well designed to help
prevent that specific kind of attack.
MCT USE ONLY. STUDENT USE PROHIBITED
07-10 Preparing for Scripting
Execution Policy
The shell’s primary security feature is its execution
policy. By default, this policy is set to Restricted.
You can run Get-ExecutionPolicy to see the
current execution policy setting.
• Run PowerShell.exe by using the –ExecutionPolicy parameter. This parameter will override local
and GPO settings, and will affect only that shell session.
Note: Notice that any user can run PowerShell.exe and use the –ExecutionPolicy
parameter. That means any informed user can deliberately override both the local execution
policy and any GPO setting. This behavior is consistent with the security goals outlined earlier,
because those goals do not extend to an informed user taking deliberate action.
• RemoteSigned lets all scripts stored on the local computer run, and lets other scripts run only if they
carry an intact digital signature, assuming that signature was created by using a certificate issued by a
trusted CA.
Digital signatures can be added to any script by using the Set-AuthenticodeSignature command. The
command requires you to install a Class 3 digital certificate on your computer. These certificates are also
known as code-signing certificates. Your certificate must be compatible with Microsoft Authenticode
technology.
Note: Code-signing certificates differ from Class 1 certificates that are used to sign or
encrypt email. Class 3 certificates typically require better proof of identity.
You can use certificates issued by a trusted internal CA or by a trusted commercial CA.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 07-11
Understanding Trust
The AllSigned and RemoteSigned execution
policy settings rely on certificates issued by a
trusted CA. So what does trust mean?
For example, suppose that a CA named Contoso exists. Your organization might review the process that
Contoso uses for identity verification. If your organization agreed that the process was thorough and
reliable, your organization could decide to trust Contoso. Doing this would let your organization to accept
and recognize all certificates issued by Contoso.
A signed script is not guaranteed to be free of malware. However, if the certificate used to sign the script
was issued by a trusted CA, you can identify the author of the script by using the script’s signature. If the
script does contain malware, the author will be known to you, and you can take appropriate actions
against the author. Because the CA verified their identity, you know who the author is. The script is no
longer anonymous.
A digital signature also guarantees the authenticity of the script. After signed, the script cannot be
changed in the slightest way without breaking the signature. A broken signature indicates that the script
was changed by someone other than the original author. A script with a broken signature is not trusted.
The critical element to trust is the identity verification process used by the CA that issued the certificate. If
a CA uses an unreliable process, that CA could be tricked into issuing false identification to a malicious
script author. You would be unable to correctly identify the author of such a script. As a security practice,
your organization should periodically review the processes of your trusted CAs, and make sure that each
CA’s process is acceptable.
MCT USE ONLY. STUDENT USE PROHIBITED
07-12 Preparing for Scripting
Windows PowerShell does not search the current folder for scripts. If you are working in the C directory,
and it contains a script named Example.ps1, you cannot run the script by using this command:
PS C:\> Example
You must provide either a relative or absolute path to run the script. Both examples are correct:
PS C:\> ./Example
PS C:\> C:\Example
The first example uses a relative path, where ./ specifies the current directory. The second example uses an
absolute path. This syntax differs from commands that are loaded in memory, because commands are not
preceded by a path.
Note: Tab completion can make it easier to run a script that is in the current directory.
Type all or part of the script’s file name, and press the Tab key. Windows PowerShell will
complete the file name and add a relative path. You can then press Enter to run the script.
Demonstration Steps
1. Determine the current execution policy.
Question: What happens if you try to run a script that exists in the current directory, but you
do not provide an absolute or relative path?
MCT USE ONLY. STUDENT USE PROHIBITED
07-14 Preparing for Scripting
Objectives
After completing this lab, students will be able to:
Lab Setup
Estimated Time: 10 minutes
Password: Pa$$w0rd
The changes that you make during this lab will be lost if you revert your virtual machines at another time
during class.
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must
follow these steps:
1. On the host computer, move the pointer over the bottom left corner of the taskbar, click Start, and
then click Hyper-V Manager on the Start screen.
2. In Hyper-V® Manager, click 10961A-LON-DC1, and in the Actions pane, click Start.
3. In the Actions pane, click Connect. Wait until the virtual machine starts.
c. Domain: ADATUM
2. Run a script
2. In the Virtual Machines list, right click 10961A-LON-DC1, and then click Revert.
Results: After completing this exercise, you will have configured and tested the execution policy on a
computer.
Use Group Policy to configure the execution policy in your environment. Group Policy offers a
centralized and easier way to consistently configure this important security setting.
Review Question(s)
Question: Do organizations typically use a single execution policy throughout their
environment?
Module08
Moving from Command to Script to Module
Contents:
Module Overview 08-1
Module Overview
In this module, you will learn to package a Windows PowerShell™ command in a script module. Script
modules are an effective way to share commands with coworkers and colleagues. With script modules,
you can make complex commands available to someone with less technical expertise, and you can more
easily reuse the commands.
Additional Reading: Some of the techniques in this module are further documented at
http://technet.microsoft.com/en-us/library/hh847806.
Objectives
After completing this module, students will be able to:
Lesson 1
Moving from Command to Script
In this lesson, you will be given a Windows PowerShell command that works perfectly. You will learn to
identify its changing values, create parameters for those values, and create and test a parameterized script
that implements the command.
Lesson Objectives
After completing this lesson, students will be able to:
• Identify values in a command that might change every time the command is used
For example, suppose that you are asked to create a tool that can be used by your Help Desk. The tool
must retrieve the 50 most recent Security event log entries from a designated computer. The tool must
retrieve only event log entries that have a specified event identification (ID). You might create the
following command as the basis for this new tool:
This command uses values such as localhost and 4624 that will not always be used when the final tool is
run. By starting with these test values, you can make sure that the command works correctly.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 08-3
Note: The preceding example may require that you manually start the Remote Registry
Service if it is not started.
These values are localhost and 4624. Remember that the tool is supposed to retrieve designated event
IDs from a specified computer to make both of those values changeable. The tool is always supposed to
retrieve event log entries from the Security event log, and is always supposed to retrieve no more than 50
entries. That means the values Security and 50 are not changeable. Those can be left alone.
Note: You cannot use the [CmdletBinding()] attribute unless you also use a Param()
block. The Param() block can be empty if your script will not need to use any input parameters.
You can also define a default value for parameters. A default value is a good idea when the value might
have to change only occasionally, but will usually be the same value each time the script is run.
MCT USE ONLY. STUDENT USE PROHIBITED
08-4 Moving from Command to Script to Module
You can also identify some or all parameters as being mandatory. When you identify a parameter as
mandatory, Windows PowerShell will prompt for a value when the person running the script does not
provide one in advance. Default values are ignored when a parameter is marked as mandatory.
For example, you might now have a script that looks as follows:
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True)]
[string]$ComputerName,
[int]$EventID = 4624
)
Get-EventLog -LogName Security -ComputerName $ComputerName |
Where EventID -eq $EventID |
Select -First 50
Notice that the parameter names have also been used instead of the old test values. The Param() block
defines the parameters, and then you can use the parameters instead of the test values in your command.
Note: Your parameter names will appear however you type them in the Param() block.
Although Windows PowerShell is not case-sensitive, this example used $ComputerName so that
the parameter would be displayed and be more consistent with cmdlets that have a –
ComputerName parameter.
Note: In this example, the script’s $ComputerName parameter is being passed as a value
to the –ComputerName parameter of the Get-EventLog command. There is no technical reason
for these two to share the same name. However, using $ComputerName makes the script
parameter consistent with the parameters of other Windows PowerShell commands.
Windows PowerShell gives you some flexibility in how you format the Param() block. The one required
rule is that each parameter be separated from the next by a comma. The last parameter is not followed by
a comma. The following is acceptable:
[CmdletBinding()]
Param([Parameter(Mandatory=$True)] [string]$ComputerName, [int]$EventID = 4624)
Most experienced users prefer the first example because it is easier to read and to maintain.
Demonstration Steps
1. Start with the file E:\ Mod08\Democode\Param1.ps1, which contains an existing, working command.
Best Practice: You may also discover the Write-Host command. It is not the correct way
to create status messages in a script. Write-Host can be used correctly only in a few scenarios.
You should avoid using the command if possible.
By default, Windows PowerShell does not display verbose output when you run the script. You must add
the –verbose parameter when you are running the script to enable the verbose output.
Demonstration Steps
1. Ensure that the local execution policy is set to RemoteSigned.
4. Run the script and allow for the verbose output to be suppressed.
<#
.SYNOPSIS
Retrieves network adapter information from a computer.
.DESCRIPTION
Uses CIM to retrieve information about physical adapters only.
.PARAMETER ComputerName
The name of the computer to query.
.EXAMPLE
.\Get-NetAdapterInfo.ps1 -ComputerName LON-DC1 -Verbose
#>
Note: The comment-based help keywords like .SYNOPSIS and .EXAMPLE are not case-
sensitive. However, it is a best practice to type them in all uppercase letters.
Demonstration Steps
1. Add comment-based help to the script E:\Mod08\Democode\Param3.ps1.
Objectives
After completing this lab, students will be able to:
Lab Setup
Estimated Time: 30 minutes
Password: Pa$$w0rd
The changes that you make during this lab will be lost if you revert your virtual machines at another time
during class.
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must
follow these steps:
1. On the host computer, move the pointer over the bottom left corner of the taskbar, click Start, and
then click Hyper-V Manager on the Start screen.
2. In Hyper-V® Manager, click 10961A-LON-DC1, and in the Actions pane, click Start.
3. In the Actions pane, click Connect. Wait until the virtual machine starts.
b. Password: Pa$$w0rd
c. Domain: ADATUM
@{n='FreeSpace(MB)';e={"{0:N2}" -f ($PSItem.FreeSpace /
1MB)}},
@{n='Size(GB)';e={"{0:N2}" -f ($PSItem.Size / 1GB)}},
@{n='FreePercent';e={"{0:N2}%" -f ($PSItem.FreeSpace /
$PSItem.Size * 100)}}
You have to test this command and make sure that it works correctly before you use the command in a script.
If you do not want to type the command, you will find it in E:\Mod08\Labfiles\LabA\Exercise1.ps1.
2. Test the command and make sure that it runs without error.
Results: After completing this exercise, you will have tested the command and verified its functionality.
2. Identify two values in this command that might have to change every time someone runs the
command.
2. Replace the fixed values 3 and localhost with $DriveType and $ComputerName respectively.
2. For the ComputerName prompt, type LON-CL1, and then press Enter.
Results: After completing this exercise, you will have identified and parameterized changing values in the
command.
Results: After completing this exercise, you will have changed your script so that it produces verbose
output.
MCT USE ONLY. STUDENT USE PROHIBITED
08-10 Moving from Command to Script to Module
a. Synopsis
b. Description
c. ComputerName parameter
d. DriveType parameter
e. Example
Results: After completing this exercise, you will have added documentation to your script by using
comment-based help.
Question: What are some advantages of using comment-based help to document a script?
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 08-11
Lesson 2
Moving from Script to Function to Module
In this lesson, you will take a working, parameterized script and package it as a reusable tool. You will
begin by wrapping the script’s commands in a function. A function is one kind of Windows PowerShell
command, and by creating one, you will be able to include multiple commands inside a single file. You
will then structure that file as a script module that can be discovered and loaded by Windows PowerShell,
and shared with colleagues or coworkers.
Lesson Objectives
After completing this lesson, students will be able to:
Basically, you make a function by wrapping all the contents of your script in a function declaration. A
declaration consists of the keyword function followed by a function name. Function names should be
consistent with the Windows PowerShell verb-noun naming convention.
[CmdletBinding()]
Param(
[string]$ComputerName,
[int]$EventID
)
Get-EventLog -LogName Security -ComputerName $ComputerName |
Where EventID -eq $EventID |
Select -First 50
function Get-SecurityEvents {
[CmdletBinding()]
MCT USE ONLY. STUDENT USE PROHIBITED
08-12 Moving from Command to Script to Module
Param(
[string]$ComputerName,
[int]$EventID
)
Get-EventLog -LogName Security -ComputerName $ComputerName |
Where EventID -eq $EventID |
Select -First 50
}
Notice that the contents of the function are indented, helping make it visually obvious what commands
belong to that function.
If your script includes comment-based help, include that help as the first thing inside the function. There
are other areas where Windows PowerShell allows for comment-based help to be added, but adding the
help immediately inside the beginning of the function is the easiest and has the fewest restrictions.
Understanding Scope
Scope is a Windows PowerShell feature that
defines containers around certain shell elements.
The following items have their own scope:
Scope is a complex topic, and complete coverage of scope is not included in this course. You can learn
more about scope by running help about_scope –ShowWindow in Windows PowerShell. For now, you
have to remember that everything done inside a script can exist only until that script finishes running.
That means that you have to make some changes to your script if you want to test your function.
Demonstration Steps
1. Open the file E:\Mod08\Democode\Function1.ps1.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 08-13
C:\Users\<username>\Documents\WindowsPowerShell\Modules;C:\Windows\system32\WindowsPo
werShell\v1.0\Modules
You can view the variable on your computer by running Get-Content Env:\PSModulePath.
Note: One of the default module locations does not actually exist by default. The location
in your Documents folder must be manually created before you can save modules there. You
should not save modules in the System32 path. That location is reserved for modules created by
Microsoft®.
If you have a script that you want to save as a script module, you have to decide on a unique module
name. For example, MyTools is a possible module name. Module names should contain only letters and
numbers, and no spaces or punctuation. If you selected MyTools as your module name, you would save
the file as:
C:\Users\<username>\Documents\WindowsPowerShell\Modules\MyTools\MyTools.psm1
Notice that the module must be saved with a .psm1 file name extension, and that the file must be in a
subfolder that has the module name. This is a very common point of confusion. For example, if the
module name is MyTools, the file name must be MyTools.psm1 and it must be saved as
\Modules\MyTools\MyTools.psm1, so that the file name and its containing folder name are the same.
Note: Use caution when you save script modules in the Windows PowerShell ISE. If you just
click Documents in the Save As dialog box, you are accessing the whole Documents Library. You
should expand the library node and make sure that you have selected the Documents folder,
instead of the Public Documents folder.
MCT USE ONLY. STUDENT USE PROHIBITED
08-14 Moving from Command to Script to Module
Demonstration Steps
1. Create the Windows PowerShell Modules folder.
The prompt also offers the option to cancel the script or function.
Write-Debug is not the most flexible or mature debugging technology in Windows PowerShell. However,
it is one of the easier areas to start debugging. Many Windows PowerShell users add Write-Debug to
their scripts as they are writing those scripts. Their Write-Debug commands serve as a kind of inline
documentation, and by using them, users can start debugging immediately if they encounter a problem
with their scripts.
Demonstration Steps
1. Add a debug breakpoint to the script.
5. Run the Get-NetAdaptInfo command. Specify localhost for the computer name. Do not enable
debugging.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 08-15
6. Run the Get-NetAdaptInfo command. Specify localhost for the computer name. Enable debugging.
8. Display the content of the $ComputerName variable and verify that it contains localhost.
Question: How could you set up your environment so that a set of script modules could be
shared between yourself and your coworkers?
MCT USE ONLY. STUDENT USE PROHIBITED
08-16 Moving from Command to Script to Module
Objectives
After completing this lab, students will be able to:
Lab Setup
Estimated Time: 30 minutes
Virtual Machines: 10961A-LON-DC1, 10961A-LON-CL1
Password: Pa$$w0rd
The changes that you make during this lab will be lost if you revert your virtual machines at another time
during class.
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must
follow these steps:
1. On the host computer, move the pointer over the bottom left corner of the taskbar, click Start, and
then click Hyper-V Manager on the Start screen.
2. In Hyper-V® Manager, click 10961A-LON-DC1, and in the Actions pane, click Start.
3. In the Actions pane, click Connect. Wait until the virtual machine starts.
o Password: Pa$$w0rd
o Domain: ADATUM
<#
.SYNOPSIS
Retrieves disk space information.
.DESCRIPTION
Retrieves disk information from a single computer.
.PARAMETER ComputerName
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 08-17
You now want to convert that script to a function, in preparation for packaging the script as a script
module.
This command will execute the function when you run the script.
Results: After completing this exercise, you will have converted the code in your script into a function.
function Get-DiskInfo {
<#
MCT USE ONLY. STUDENT USE PROHIBITED
08-18 Moving from Command to Script to Module
.SYNOPSIS
Retrieves disk space information.
.DESCRIPTION
Retrieves disk information from a single computer.
.PARAMETER ComputerName
The name of the computer to query.
.PARAMETER DriveType
The type of drive to query. Defaults to 3, representing local fixed disks.
.EXAMPLE
.\Get-DiskInfo -ComputerName localhost -Verbose
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True)][string]$ComputerName,
[int]$DriveType = 3
)
Write-Verbose "Getting drive types of $DriveType from $ComputerName"
Get-CimInstance -ClassName Win32_LogicalDisk -Filter "DriveType=$DriveType" `
-ComputerName $ComputerName |
Select-Object -Property @{n='DriveLetter';e={$PSItem.DeviceID}},
@{n='FreeSpace(MB)';e={"{0:N2}" -f ($PSItem.FreeSpace /
1MB)}},
@{n='Size(GB)';e={"{0:N2}" -f ($PSItem.Size / 1GB)}},
@{n='FreePercent';
e={"{0:N2}%" -f ($PSItem.FreeSpace / $PSItem.Size *
100)}}
}
Get-DiskInfo -ComputerName localhost
Results: After completing this exercise, you will have saved your script as a script module.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 08-19
1. Add a breakpoint
2. Run the Get-DiskInfo command. Specify localhost as the computer name, and do not enable
debugging.
3. Run the Get-DiskInfo command. Specify localhost as the computer name, and enable debugging.
Results: After completing this exercise, you will have added debugging breakpoints to the MyTools script
module.
Lesson 3
Implementing Basic Error Handling
In this lesson, you will learn to identify predictable errors in a script, and to add code and commands to
gracefully handle those errors when they occur.
Lesson Objectives
After completing this lesson, students will be able to:
If you assume that the computer BAD does not exist on the network, Get-WmiObject will have an error
when it tries to query that computer. However, the command could potentially continue with the next
computer, LON-DC1. The error is therefore a non-terminating error.
$ErrorActionPreference
Windows PowerShell has a built-in, global variable named $ErrorActionPreference. When a command
has a non-terminating error, the command checks that variable to see what it should do. The variable can
have one of four possible values:
• Continue is the default, and tells the command to display an error message and to continue to run.
• SilentlyContinue tells the command to display no error message, but to continue running.
• Inquire tells the command to display a prompt asking the user what to do.
• Stop tells the command to treat the error as terminating and to stop running.
For example:
$ErrorActionPreference = 'Inquire'
If you intend to trap an error within your script so that you can handle the error, commands must use the
Stop action. You can trap and handle only terminating errors. However, it is considered a poor practice to
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 08-21
change $ErrorActionPreference if the error that you expect will be produced by a Windows PowerShell
command.
-ErrorAction Parameter
All Windows PowerShell commands have an –ErrorAction parameter. This parameter has the alias –EA.
The parameter accepts the same values as $ErrorActionPreference, and the parameter overrides the
variable for that particular command. If you expect an error occurring on a command, you therefore use –
ErrorAction to set that command’s error action to Stop. Doing this lets you trap and handle the error for
that command, but leaves all other commands to use the action in $ErrorActionPreference. For example:
The only time that you will usually modify $ErrorActionPreference is when you expect an error outside
of a Windows PowerShell command, such as when you are executing a method:
In this example, the Kill() method might have an error. But because it is not a Windows PowerShell
command, it does not have an –ErrorAction parameter. You would instead set $ErrorActionPreference
to Stop before running the method, and then set the variable back to Continue after you run the
method.
Demonstration Steps
1. Run a command by using the Continue error action.
Try...Catch Constructs
Windows PowerShell uses the
Try…Catch…Finally construct to implement error
handling.
• The Catch section is optional, and will run if an error happens in the Try section.
• The Finally section is optional, and will run regardless of whether an error happens in the Try section.
If it is used, Finally must come after Catch.
You do not have to use both Catch and Finally. However, you must use at least one of them. You can
have multiple Catch sections, configured so that each section handles a different kind of error. For more
information about how to do this, read the About_Try_Catch_Finally Help file in Windows PowerShell.
Here is an example:
Try {
Get-WmiObject –Class Win32_Service –ComputerName $name –ErrorAction Stop
} Catch {
Write-Verbose "Error connecting to $name"
}
Note: The Finally section of this construct is rarely used. That is why the construct is known
as Try…Catch instead of Try…Catch…Finally.
Remember that setting –ErrorAction to Stop will turn any error into a terminating error. That means the
command will not continue to process. For this reason, you will usually write your script so that the
command is processing only one thing at a time. In this example, that means $name would contain only
one computer name at a time, so if one computer name fails, the command is not skipping anything.
Demonstration Steps
• Add a command to a Try…Catch construct.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 08-23
Logging Errors
Although –ErrorAction tells a command what to
do when an error happens, it does not capture the
error. There are two ways to capture an error in
Windows PowerShell.
When you run a Windows PowerShell command, a better approach is to use the –ErrorVariable
parameter (which uses the alias –EV). The parameter accepts a variable name as its value, and if an error
happens, the error is stored in that variable.
Note: Variable names do not include a dollar sign ($). Make sure not to include a dollar
sign when specifying a variable name to –ErrorVariable.
For example:
Try {
Get-WmiObject –Class Win32_Service –ComputerName $name –ErrorAction Stop –
ErrorVariable MyErr
} Catch {
Write-Verbose "Error connecting to $name"
$MyErr | Out-File C:\Errors.txt
}
In this example, the error is captured to $MyErr and written to the file C:\Errors.txt.
Demonstration Steps
• Use –ErrorVariable to add error logging to a script.
Question: The Try…Catch construct was introduced in Windows PowerShell 2.0. An earlier
construct was introduced in Windows PowerShell 1.0, and is still supported in Windows
PowerShell 3.0. Do you know what that older construct is?
MCT USE ONLY. STUDENT USE PROHIBITED
08-24 Moving from Command to Script to Module
Objectives
After completing this lab, students will be able to:
Lab Setup
Estimated Time: 30 minutes
The changes that you make during this lab will be lost if you revert your virtual machines at another time
during class.
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must
follow these steps:
1. On the host computer, move the pointer over the bottom left corner of the taskbar, click Start, and
then click Hyper-V Manager on the Start screen.
2. In Hyper-V® Manager, click 10961A-LON-DC1, and in the Actions pane, click Start.
3. In the Actions pane, click Connect. Wait until the virtual machine starts.
4. Sign in by using the following credentials:
o Password: Pa$$w0rd
o Domain: ADATUM
3. Run the Get-DiskInfo command. Specify BAD for the computer name, and enable verbose output.
Results: After completing this exercise, you will have added error handling to an existing function.
3. Run the script and notice the behavior when an incorrect computer name is specified.
Results: After completing this exercise, you will have added error handling to a function that someone
else wrote.
Question: In one of the demonstrations, you saw an example of how to add error logging to
a script. That example used a static file name. In a production environment, a user might
want the ability to specify the name of the file where errors would be logged. How could you
provide that ability?
MCT USE ONLY. STUDENT USE PROHIBITED
08-26 Moving from Command to Script to Module
Lesson 4
Using Basic Scripting Constructs
In this lesson, you will learn about three of Windows PowerShell’s scripting language constructs. These are
the most frequently used elements of Windows PowerShell’s scripting language.
Lesson Objectives
After completing this lesson, students will be able to:
The If Construct
The If construct is used to make logical decisions.
Its complete syntax looks as follows:
• The If section is mandatory. A condition that evaluates to either True or False must be enclosed in
parentheses. Curly braces then enclose a script block. The script block contains the command or
commands that will run if the condition evaluates to True.
• Zero or more ElseIf sections are next. Each of these has its own condition and script block. You are
not required to have any ElseIf sections, and you may have as many as you must have.
• An optional Else section comes last. It does not have a condition. However, it does have a script
block.
The conditions are evaluated in order. When a condition is found that evaluates to True, the shell executes
the corresponding script block and stops evaluating any other conditions. If no conditions evaluate to
True, and if an Else section exists, the Else section’s script block will be executed.
As a best practice, the command or commands within each script block should be indented one level. You
can create this indentation by using the Tab key in the Windows PowerShell ISE. The preceding formatting
is one of two common ways to format this and other constructs. The following is the other common
formatting approach:
{
# Condition 1
}
Else
{
# Condition 2
}
Note: In the Windows PowerShell ISE, you can use the mouse pointer to select multiple
lines of text. You can then press Tab or Shift+Tab to increase or decrease the indentation level for
the selected lines.
Demonstration Steps
1. Write a command that retrieves information about drive C.
2. Based on the value of the drive’s DriveType property, display a message about the type of drive.
The Switch construct can also match by using wildcard patterns, regular expressions, and so on. To do
this, you must specify a parameter that tells the construct what kind of match you want. For information
about the available options, run help about_switch in Windows PowerShell.
The construct differs from If in one important way. It will execute each matching script block, instead of
executing only the first matching condition. For example:
In this example, LON-CL1 will display both Computer is a client and Computer is the first one because
both conditions match. You can use the Break keyword to exit the construct. This prevents multiple
matches. For example:
LON-CL1 will now display only Computer is a client. The computer LON-DC1 would display Computer is
in NYC and Computer is a DC.
In this example, Names.txt has one computer name per line. Those are loaded into $ComputerName as
individual String objects to make $ComputerName a collection. The ForEach construct enumerates
through those one at a time. The variable on the left side of the in keyword will contain one object at a
time from the variable on the right side of the keyword. In other words, one computer name at a time will
be taken out of $ComputerName and added into $name. The command or commands in the script
block will execute one time for each object in the $ComputerName variable.
Because most Windows PowerShell users prefer scripts that are easy to read and maintain, it is a common
practice to use similar variable names in the ForEach construct. For example:
$Services = Get-Service
ForEach ($Service in $Services) {
Write "The current service is $($service.name)"
}
However, this naming practice is not a technical requirement. The following example also works correctly:
$x = Get-Service
ForEach ($z in $x) {
Write "The current service is $z"
}
This second example is not as easy to read, because the names $x and $z do not provide any indication or
reminder of what the variables contain.
Demonstration Steps
• Use ForEach to enumerate through a list of computer names.
Question: Are you familiar with any scripting language constructs from other scripting
languages that might also be present in Windows PowerShell?
MCT USE ONLY. STUDENT USE PROHIBITED
08-30 Moving from Command to Script to Module
Objectives
After completing this lab, students will be able to:
Lab Setup
Estimated Time: 60 minutes
Password: Pa$$w0rd
The changes that you make during this lab will be lost if you revert your virtual machines at another time
during class.
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must
follow these steps:
1. On the host computer, move the pointer over the bottom left corner of the taskbar, click Start, and
then click Hyper-V Manager on the Start screen.
2. In Hyper-V® Manager, click 10961A-LON-DC1, and in the Actions pane, click Start.
3. In the Actions pane, click Connect. Wait until the virtual machine starts.
o Password: Pa$$w0rd
o Domain: ADATUM
Results: After completing this exercise, you will have tested an existing command and identified
changeable values.
3. Copy and paste the contents of the Exercise1.ps1 script into the Get-OSInfo function.
Results: After completing this exercise, you will have created a parameterized function by using the
provided command.
1. Modify a parameter
2. Modify the command that uses the computer name to use the enumerator variable instead of the
computer name parameter.
Results: After completing this exercise, you will have changed a function to accept multiple computer
names as input.
2. Run the Get-OSInfo command. For the computer name, specify LON-CL1,BAD,localhost.
2. In the Virtual Machines list, right click 10961A-LON-DC1, and then click Revert.
Results: After completing this exercise, you will have added error handling to a function.
Question: What if you need to write a function whose output combines information from
multiple sources?
MCT USE ONLY. STUDENT USE PROHIBITED
08-34 Moving from Command to Script to Module
Lesson 5
Exploring Other Scripting Features
In this lesson, you will learn about some additional scripting-related capabilities of Windows PowerShell.
This lesson is not meant to be a comprehensive examination of these features. Instead, this lesson is
intended to give you a brief overview that provides a starting point for additional independent
exploration.
Lesson Objectives
After completing this lesson, students will be able to:
PSBreakpoints
PSBreakpoints are another, more advanced way to
debug scripts. You can set these breakpoints
visually in the ISE host application, or by running
commands in either the console host or the ISE
host. Breakpoints are contained within the
Windows PowerShell session. Therefore, a
breakpoint set in one Windows PowerShell
window will not be effective in another Windows
PowerShell window.
To see a list of commands that are available for working with breakpoints, run Get-Command –Noun
PSBreakpoint. For a general overview of debugging when you use PSBreakpoints and other techniques,
run Help About_Debuggers.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 08-35
• You can define aliases for parameter names. For example, you might define a –HostName alias for a
–ComputerName parameter.
Advanced functions can also use any of the features that are available to regular functions and scripts.
You can define customized default formatting views, type extensions, and use many different other
techniques to make your functions work exactly the way that you want. These topics are beyond the
scope of this course, but running help *function* in the shell will provide a list of Help files that can serve
as a good starting point for independent exploration.
Each of these is documented in a Help file within Windows PowerShell. For example, to learn more about
the For construct, run Help about_For.
Question: The main purpose for PSBreakpoints is to help debug scripts. You have also
learned about the Write-Debug command, which serves a similar purpose. What other
approaches to debugging are you familiar with?
MCT USE ONLY. STUDENT USE PROHIBITED
08-36 Moving from Command to Script to Module
As you start to write functions, take the time to format commands and code in the correct way.
Every time that you begin a new construct, indent the contents of that construct. This technique
helps make it visually clearer which code belongs to the construct to make both maintenance
and debugging easier.
Review Question(s)
Question: What kinds of tasks do you want to automate immediately using a script module?
Module09
Administering Remote Computers
Contents:
Module Overview 09-1
Module Overview
Windows PowerShell™ remoting is a technology that enables you to connect to one or more remote
computers and instruct them to run commands on your behalf. It is a powerful and flexible technology,
and one that is quickly becoming the foundation for administrative communications in a Windows-based
environment. For example, the graphical Server Manager console in Windows Server® 2012 relies on
remoting to communicate with servers even to communicate with the local computer on which the
console is running! Past versions of the operating system have included remoting, but its use was largely
optional. Now the technology is quickly becoming a mandatory component of every environment.
Objectives
After completing this module, students will be able to:
Lesson 1
Using Basic Remoting
Remoting is a complex technology in its own right, and to use it appropriately, you have to learn a bit about it.
Actually working with remoting is fairly straightforward as soon as you understand the underlying concepts, and in
this lesson you will begin to use remoting to perform administration on remote computers.
Lesson Objectives
After completing this lesson, students will be able to:
• Explain the difference between remoting and other forms of remote administration
• Describe remoting security and privacy features
WinRM is used for Windows PowerShell remoting, and it is also able to handle communications for other
applications. For example, on a default Windows Server 2012 installation, WinRM handles
communications for 64-bit Windows PowerShell, 32-bit Windows PowerShell, and two Server Manager
components. In the future, it is likely that more and more applications, specifically on servers, will register
with WinRM so that it will handle their administrative communications needs.
In this course, you will use remoting mainly in its default configuration, using HTTP on port 5985.
Remoting can be configured to allow for or to require encryption based on Secure Sockets Layer (SSL), by
using the HTTPS protocol, and defaults to port 5986 when doing this. However, to use HTTPS, a receiving
MCT USE ONLY. STUDENT USE PROHIBITED
09-4 Administering Remote Computers
computer must be configured to have an SSL certificate, which makes the remoting configuration
somewhat more complex.
Architecture
Remoting starts with the WinRM service. It registers one or more listeners. Each listener accepts incoming
traffic through either HTTP or HTTPS, and each listener can be bound to a single local IP address or to
multiple IP addresses. There is no dependency on Microsoft® Internet Information Services (IIS). This
means that IIS does not have to be installed for WinRM to function.
Incoming traffic includes an envelope that indicates the traffic’s intended destination, or endpoint. In
Windows PowerShell, these endpoints are also known as session configurations. Each endpoint is
associated with a specific application, and when traffic is directed to an endpoint, WinRM starts the
associated application, hands off the incoming traffic, and waits for the application to complete its task.
The application can pass data back to WinRM, and WinRM handles transmitting that data back to the
originating computer.
In a Windows PowerShell scenario, you would send commands to WinRM, which would be executed by
WinRM (the process is listed as Wsmprovhost in the remote computer’s process list). Windows PowerShell
would then execute those commands, and convert (or serialize) the resulting objects, if any, into XML. The
XML text stream is handed back to WinRM, which transmits it to the originating computer. That
computer’s copy of Windows PowerShell deserializes the XML back into static objects. This enables the
command results to behave much like any other objects within the Windows PowerShell pipeline.
Windows PowerShell can register multiple endpoints, or session configurations, with WinRM. In fact, a 64-
bit operating system will register an endpoint for both the 64-bit Windows PowerShell host and the 32-bit
host. This is by default. As you will see later in this module, you can also create your own custom
endpoints that have highly precise permissions and capabilities assigned to them.
Remoting is a generalized way to transmit any command to a remote computer for local execution. The
command that you execute does not have to be present on the computer that initiates the connection;
only the remote computers must be able to know about the command and to run it. The purpose of
remoting was to reduce or eliminate the need for individual command authors to code their own
communications protocols. Many command authors already had to do this to ship their products. This is
why many different protocols and technologies are being used currently.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 09-5
Remoting Security
By default, the endpoints created by Windows
PowerShell only allow for connections by
members of a particular group. On Windows
Server 2012 and Windows 8, this group is the
Remote Management Users group, as well as the
local Administrators group. On earlier operating
system versions, members of the local
Administrators group are allowed by default. In
common practice, this means that remoting can
be used only by domain administrators. Each
endpoint does have a Security Access Control List
(SACL) that can be changed to control exactly
who can connect to it.
The default remoting behavior is to delegate your logon credentials to the remote computer, although
you do have the option of specifying alternative credentials when you make a connection. Regardless, the
remote computer uses those credentials to impersonate you, performing whatever tasks that you have
specified by using those credentials. This behavior means that you will be able to do whatever you are
allowed to do, and if those actions would usually be audited, they will be audited when they are
performed through remoting also. Basically, remoting is security transparent, meaning it adds nothing,
and removes nothing, from your environment’s existing security. Whatever you could do when you were
physically standing in front of the remote computer, you will be permitted to do through remoting, and
nothing more.
Note: A special exception is made for the computer name localhost, which enables you to
use it to connect to the local computer without any other configuration changes.
MCT USE ONLY. STUDENT USE PROHIBITED
09-6 Administering Remote Computers
Best Practice: Avoid using the TrustedHosts list unless absolutely necessary. Configuring a
nondomain computer to use HTTPS is a more secure long-term solution.
Privacy
By default, remoting uses HTTP, which does not offer privacy (encryption) for the contents of your
communications. However, Windows PowerShell can and does apply application-level encryption by
default. This means that your communications do receive a degree of privacy and protection. On internal
networks, this application-level encryption is generally sufficient for most organizations’ requirements.
Credentials are not typically transmitted in clear text.
In a domain environment that uses the default Kerberos authentication protocol, credentials are sent in
the form of encrypted Kerberos tickets that do not include passwords.
When you connect by using HTTPS, the entire channel is encrypted by using the encryption keys of the
remote computer’s SSL certificate so that even if the Basic authentication protocol is used, passwords are
not transmitted in the clear.
When you connect, by using HTTP and the Basic authentication protocol, to a computer that is not
configured for HTTPS, credentials may be transmitted in clear text, including passwords.
The last situation would occur when you connect to a nondomain computer that you add to your local
TrustedHosts list. Because credentials must be passed in clear-text in that scenario, you should ensure that
you connect to a nondomain computer only on a controlled and protected network subnet, such as a
subnet specifically designated for new computer provisioning. If you have to routinely connect to a
nondomain computer, you should configure it to support HTTPS so that credentials are not transmitted in
clear-text.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 09-7
Enabling Remoting
Be aware that remoting must be enabled only on
computers that will receive incoming connections.
No configuration is needed to enable outgoing
communications (except to make sure that any
local firewall will allow the outgoing traffic).
This command will fail on client computers where one or more network connections are set to Public
(instead of Work or Home). You can override this failure by adding the –SkipNetworkProfileCheck
parameter. However, be aware that the Windows Firewall will not allow exceptions when you are
connected to a “Public” network.
One-to-one remoting is engaged by using the Enter-PSSession command, combined with its –
ComputerName parameter. Other parameters let you perform basic customization of the connection;
these are covered later in this module.
MCT USE ONLY. STUDENT USE PROHIBITED
09-8 Administering Remote Computers
When you are connected, the Windows PowerShell prompt changes to indicate the computer that you are
connected to. Run Exit-PSSession to close the session and return to the local command prompt. If you
close Windows PowerShell while connected, the connection will close on its own.
Usage Scenarios
You can use one-to-many remoting in two main ways:
This technique sends the contents of the designated script file (with a .ps1 file name extension) to the
computers that are listed. The local computer opens the file and reads its contents. The remote computers
do not have to have direct access to the file. This technique is useful for sending a large file of commands,
such as a complete script.
Note: Within any script block, including the script block provided to the –ScriptBlock
parameter, you can use a semicolon (;) to separate multiple commands. For example, { Get-
Service ; Get-Process } will run Get-Service, and then run Get-Process.
Throttling
By default, Windows PowerShell will connect to only 32 computers at the same time. If you list more than
32 computers, the excess will be queued. As some initial computers complete and return their results,
computers will be pulled from the queue and contacted.
You can alter this behavior by using the –ThrottleLimit parameter of Invoke-Command. Raising the
number does not put additional load on the remote computers. However, it does put an additional load
on the computer where Invoke-Command was run. Each concurrent connection is basically a thread of
Windows PowerShell. Therefore, raising the number consumes memory and processor on the local
computer.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 09-9
Passing Values
The contents of the script block or file are transmitted as literal text to the remote computers that run
them exactly as is. No parsing of the script block or file is performed by the computer where Invoke-
Command was run. Consider the following example:
$var = 'BITS'
Invoke-Command –ScriptBlock { Get-Service –Name $var } –Computer LON-DC1
In this scenario, the variable $var is being set on the local computer. It is not inserted into the script block.
In other words, LON-DC1 is being asked to retrieve a service whose name is equal to the one in the
variable $var. SERVER2, however, will have no idea what $var contains, as b has not been defined on
LON-DC1. This is a common mistake made by newcomers. There is a specific way to handle this situation,
and it will be covered in the next lesson.
This command will run the Get-Credential cmdlet on the remote computer. Try running Get-Credential
on your local computer, and notice that it uses a graphical dialog box to prompt for the credential. Will
that work when run on a remote computer? If you ran the preceding command on 100 remote
computers, would you be prompted for 100 credentials?
This command runs Get-Credential on your local computer, and runs it only once. The resulting object is
passed into the $c parameter of the script block, enabling each computer to use the same credential.
These examples illustrate the importance of writing remoting commands carefully. By using a combination
of remote execution and local execution, you can achieve a variety of useful goals.
Note: You will learn more about credential objects in Module 12, “Using Profiles and
Advanced Windows PowerShell Techniques.”
Persistence
Using the technique outlined here, every time that you use Invoke-Command, the remote computer
creates a new Windows PowerShell instance, runs your command or commands, returns the results to you,
and then closes that Windows PowerShell instance. Each successive Invoke-Command, even if made to
the same computers, is like opening a whole new Windows PowerShell window. Any work done by a
previous session will not exist unless it was saved to disk or some other persistent storage. For example:
In this example, the second Invoke-Command would fail, because it is dependant on a variable that was
created in a previous instance of Windows PowerShell. When the first Invoke-Command finished
running, that variable was lost. You can create a persistent instance of Windows PowerShell on a remote
MCT USE ONLY. STUDENT USE PROHIBITED
09-10 Administering Remote Computers
computer so that you can successfully send successive commands to it, and you will learn about that
technique later in this module.
• -ComputerName ONE,TWO,THREE
This reads a comma-separated values (CSV) file that is named Computers.csv. It contains a column
named“Computer that contains computer names.
This queries every computer object in Active Directory Domain Services (which can take significant time in
a large domain).
This command does not provide a –ComputerName parameter to Invoke-Command. Therefore, the
command runs on the local computer. The local computer will run Get-Service, and tell Get-Service to
connect to computers named ONE and TWO. The protocols used by Get-Service will be used; Windows
PowerShell remoting will not be used. Compare that with this command:
This command will use Windows PowerShell remoting to connect to computers named ONE and TWO.
Each of these computers will run Get-Service locally, returning their results by means of remoting.
Demonstration Steps
1. Ensure you are signed into the 10961A-LON-CL1 virtual machine as Adatum\Administrator with
password Pa$$w0rd.
2. Ensure you have the correct execution policy in place by runnning the command set-
executionPolicy RemoteSigned.
3. Enable remoting.
7. Get a list of the most recent 10 Security event log entries from LON-CL1 and LON-DC1.
When the XML is received by your computer, the XML is deserialized back into objects that are put in the
Windows PowerShell pipeline. When you have a Process object, piping it to Get-Member would reveal
that it is now of the type Deserialized.System.Diagnostics.Process, a related, but different, kind of
object. The deserialized object has no methods and no events.
So from a practical perspective, you should consider any data that is received through remoting to be a
static snapshot. The data is not updatable, and the objects cannot be used to take any actions. Therefore,
you will usually want to do as much processing as possible on the remote computer, where the objects are
still live objects that have methods and events. For example:
The preceding command would be a bad idea. You are receiving back Process objects; the action of
stopping will occur on the local computer, not the remote one; and this action stops any local processes
that happened to have names matching the remote ones. The correct approach would be as follows:
Here, the processing has occurred completely on the remote computer, with only the final results being
serialized and sent back. The difference between these two commands is subtle but important: make sure
that you understand the difference.
Question: Why would an administrator decide to use remoting instead of managing a
computer directly?
Lesson 2
Using Advanced Remoting Techniques
Remoting includes several advanced techniques that help achieve specific goals, or alleviate specific
shortcomings. In this lesson, you will learn about the most useful advanced techniques.
Lesson Objectives
After completing this lesson, students will be able to:
• –Credential specifies an alternative credential for the connection. This credential will be validated by
the remote computer, and must have sufficient privileges and permissions to perform whatever tasks
you intend to perform on the remote computer. This will be passed in clear-text when you are using a
non-HTTPS connection and the Basic authentication protocol.
• –ConfigurationName connects to an endpoint (session configuration) other than the default. For
example, specify “Microsoft.Windows PowerShell32” to connect to the remote computer’s 32-bit
Windows PowerShell endpoint.
• –Authentication specifies an authentication protocol: the default is Kerberos, and other options
include Basic, CredSSP, Digest, Negotiate, and NegotiateWithImplicitCredential. The protocol that you
specify must be enabled in the WS-MAN configuration on both the initiating and receiving
computers.
Additional session options can be configured by using New-PSSessionOption to create a new session
option object, and passing it to the –SessionOption parameter of Enter-PSSession or Invoke-
Command. Review the Help file for New-PSSessionOption to learn about its capabilities.
Defaults, such as the port number defaults and enabled authentication protocols, can be modified in the
drive WSMan in Windows PowerShell.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 09-13
$Log = 'Security'
$Quantity = 10
Invoke-Command –Computer ONE,TWO –ScriptBlock {
Get-EventLog –LogName $Log –Newest $Quantity
}
The problem is that the variables $Log and $Quantity have meaning only on the local computer, and
those values are not inserted into the script block prior to those values being sent to the remote
computers. The remote computers are left to try to determine what they mean. Here’s the correct syntax
for this:
$Log = 'Security'
$Quantity = 10
Invoke-Command –Computer ONE,TWO –ScriptBlock {
Param($x,$y) Get-EventLog –LogName $x –Newest $y
} –ArgumentList $Log,$Quantity
Here, the local variables are passed to the ArgumentList parameter of Invoke-Command. Within the
script block, a Param() block is created. It contains the same number of variables as the –ArgumentList
list of values, that is, two. The variables within the Param() block can be named anything that you want.
They will receive data from the ArgumentList parameter based on order. In other words, because $Log
was listed first on ArgumentList, its value will be passed to $x because it is first in the Param() block. The
variables in the Param() block can then be used inside the script block, as shown.
Note: The syntax shown in these examples will work for Windows PowerShell 2.0 and
Windows PowerShell 3.0. However, Windows PowerShell 3.0 introduces a simplified alternative
syntax. If you have a local variable $variable, and you want to include its contents in a command
that will be executed on a remote computer, you can run Invoke-Command –ScriptBlock { Do-
Something $Using:variable } –ComputerName REMOTE. The special $Using: prefix is
understood by the local computer, and $Using:variable will be replaced with the contents of the
local variable $variable.
This same technique works with the –FilePath parameter of Invoke-Command. In that case, Windows
PowerShell expects the script file to already contain a Param() block, and will attach the ArgumentList
values in the order in which they are listed.
MCT USE ONLY. STUDENT USE PROHIBITED
09-14 Administering Remote Computers
Demonstration Steps
1. Create local variables to hold data.
2. Pass the local data to the remote computers to customize command execution.
Multihop remoting
One problem with remoting is how credentials are
delegated. By default, credentials can be
delegated across only one connection, or hop.
This single delegation prevents the remote
computer from further delegating your
credentials, which might be a security risk.
The solution is to enable Credential Security Support Provider (CredSSP), a new authentication protocol
introduced with the Windows Vista® operating system and present in Windows 7 and Windows 8.
Enabling CredSSP
The CredSSP protocol must be enabled both on the initiating computer, referred to as the client, and on
the receiving computer, referred to as the server. Doing this enables the receiving computer to delegate
your credential one additional hop.
To configure the client, run Enable-WsManCredSSP –Role Client –Delegate servername. Substitute
servername with the name of the server that will be able to redelegate your credential. The server name
can contain wildcard characters, although using only * is too permissive, because you would be enabling
any computer, even an intruder’s, to redelegate your credential. Instead, consider a limited wildcard
pattern, such as *.ADATUM.com, that would limit redelegation to computers in that domain.
To configure the server, run Enable-WsManCredSSP –Role Server. No delegated computer list is needed
on the server.
These settings can also be configured through Group Policy, offering a more centralized and consistent
configuration across an enterprise.
Question: Why might you configure remoting to use ports other than the defaults?
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 09-15
Objectives
After completing this lab, students will be able to:
Lab Setup
Estimated Time: 30 minutes
Password: Pa$$w0rd
The changes that you make during this lab will be lost if you revert your virtual machines at another time
during class.
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must
follow these steps:
1. On the host computer, move the pointer over the bottom left corner of the taskbar, click Start, and
then click Hyper-V Manager on the Start screen.
2. In Hyper-V® Manager, click 10961A-LON-DC1, and in the Actions pane, click Start.
3. In the Actions pane, click Connect. Wait until the virtual machine starts.
o Password: Pa$$w0rd
o Domain: ADATUM
4. Verify that Windows PowerShell as configured several session configurations. You have to find a
command that can produce this list.
Results: After completing this exercise, you will have enabled remoting on the client computer.
1. Connect to the remote computer and install an operating system feature on it.
Task 1: Connect to the remote computer and install an operating system feature on
it
1. Ensure you are still signed into the 10961A-LON-CL1 virtual machine as Adatum\Administrator
with password Pa$$w0rd.
2. Try to establish a connection from LON-DC1 to LON-CL1. What happens, and why?
2. Establish a one-to-one remoting connection to LON-CL1 (use the computer name localhost). This is
your local computer, but this new connection creates a second user session for you on the computer.
3. Use Windows PowerShell to start a new instance of Notepad. What happens? Why?
Results: After completing this exercise, you will have connected to a remote computer and performed
maintenance tasks on it.
2. On LON-CL1, Using a keyword like adapter, find a command that can list network adapters.
3. Read the Help for the command and find a switch parameter that will limit output to physical
adapters.
4. Use remoting to run the command on LON-CL1 and LON-DC1.
2. Use remoting to retrieve a list of Process objects from LON-DC1, and pipe them to Get-Member.
3. Compare the output of the two Get-Member results.
Results: After completing this exercise, you will have run commands against multiple remote computers.
Question: Would it be possible to use remoting to connect to a client computer and run an
application that the interactive user of that computer could see?
MCT USE ONLY. STUDENT USE PROHIBITED
09-18 Administering Remote Computers
Lesson 3
Using Remoting Sessions
To this point, you have worked with remoting only in an ad hoc manner. That is, each remoting command
that you used created a connection, used it, and then closed it. You have already learned that this model
does not offer any kind of persistence of information on the remote computer. In this lesson, you will
learn how to establish and manage persistent connections to remote computers, known as sessions.
Lesson Objectives
After completing this lesson, students will be able to:
Persistent Connections
To this point, when you have run Enter-
PSSession or Invoke-Command, Windows
PowerShell has had to make the connection to the
remote computer, retrieve a copy of Windows
PowerShell running there, run whatever
commands that you specified, and then close the
remote copy of Windows PowerShell and close
the connection. This ad hoc technique offers no
persistence of information across connections,
because each connection is basically starting a
brand-new copy of Windows PowerShell.
Windows PowerShell does have the capability of
creating persistent connections that are known as sessions, or more accurately, PSSessions (the “PS”
designation signifies Windows PowerShell, and differentiates these sessions from other kinds of sessions
that might be present in other technologies, such as a Remote Desktop Services session).
Disconnected Sessions
In Windows PowerShell 3.0, sessions can also be manually disconnected, closing your connection but
leaving the remote copy of Windows PowerShell running. You can then reconnect to the session, even
from a different computer, to continue using that same copy of Windows PowerShell.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 09-19
Controlling Sessions
Every computer where remoting is enabled has a drive WSMan that includes many configuration
parameters related to session. This includes maximum session run time, maximum idle time, maximum
number of incoming connections, and maximum number of sessions per administrator. You can explore
these by running Dir WSMan:\localhost\shell, and can change them in that same location. Many of the
settings can also be controlled through Group Policy.
Creating a Session
Use New-PSSession to create a new session. You
will notice that the command contains many of
the same parameters as Invoke-Command,
including, among others, Credential, –Port, and –
UseSSL. You are creating the identical kind of
connection that Invoke-Command creates you
are just leaving this connection running, instead of
immediately closing and using it.
New-PSSession can accept multiple computer names. This causes it to create multiple session objects.
When you run the command, it outputs objects representing the newly created sessions. You will
frequently assign these to a variable to make them easier to refer to and use in the future. For example:
Using a Session
As soon as you have created a session, you can
use it. Both Invoke-Command and Enter-
PSSession can accept a session object (Invoke-
Command can accept multiple session objects)
instead of a computer name. Use the commands’
–Session parameter for this purpose. When you
do, they use the existing session instead of
creating a new connection. When your command
finishes running or you exit the session, the
session remains running and connected and ready
for future use. For example:
Or:
Demonstration Steps
1. On the LON-CL1 virtual machine, create a session to LON-DC1 and store it in a variable.
2. Create sessions to LON-CL1 and LON-DC1 and store them both in a single variable.
9. Use remoting to retrieve a list of started services from both LON-CL1 and LON-DC1, by using the
already-open sessions.
10. Close the session to LON-DC1.
Disconnected Sessions
As you have learned, Windows PowerShell can
disconnect sessions when both the initiating
computer and the remote computer are running
Windows PowerShell 3.0. Disconnecting is
typically a manual process. In some scenarios,
Windows PowerShell can automatically place a
connection into Disconnected state if the
connection is interrupted. However, if you
manually close the Windows PowerShell host
application, it will not disconnect sessions but will
instead close them. Using disconnected sessions
resembles the following process:
1. Use New-PSSession to create the new session. Optionally, use the session to run commands.
2. Run Disconnect-PSSession to disconnect the session. Pass the session object that you want to
disconnect to the command’s –Session parameter.
4. Run Get-PSSession with the –ComputerName parameter to obtain a list of your sessions running on
the specified computer.
Demonstration Steps
1. Create a session to LON-DC1. Save the session in a variable.
Implicit Remoting
Another good use of sessions is called implicit
remoting.
These problems are why so many administrators forgo installing any tools on their workstations, and
access tools directly on the server through Remote Desktop. This, unfortunately, is a terrible solution,
because it puts the server in the position of having to be a client, while at the same time providing
services to hundreds or thousands of users. The advent of Server Core, which lacks a graphical user
interface, was in part to make servers perform better and need fewer updates but that also means that
they cannot run graphical tools and consoles.
ran everything through Invoke-Command but much more convenient. Commands also run more quickly,
because commands on the server are naturally co-located with the server’s functionality and data.
You have the option of adding a prefix to the noun of the commands that you import in this manner.
Doing this can make it easier, for example, to have multiple versions of the same commands loaded at the
same time, without causing a naming collision. For example, you might import both Microsoft Exchange
Server 2010 and Microsoft Exchange Server 2013 commands, adding a 2010 and 2013 prefix, respectively.
This enables you to run both sets of commands. In reality, each would be running on their respective
servers, enabling you to run both sets (perhaps in a migration scenario) side-by-side.
Help also works for commands that are running through implicit remoting. However, the Help files are
drawn through the same remoting session as the commands themselves. Therefore, the remote computer
must have an updated copy of its Help files. This can be a concern on servers, because they may not be
used all that frequently, and nobody may have run Update-Help on them to pull down the latest Help
files.
Demonstration Steps
1. On 109061A-LON-CL1, establish a remoting session to LON-DC1 and save it in a variable.
3. Import the ActiveDirectory module from LON-DC1, adding the prefix Rem to the imported
commands’ nouns.
Objectives
After completing this lab, students will be able to:
Lab Setup
Estimated Time: 30 minutes
Password: Pa$$w0rd
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must
follow these steps:
1. On the host computer, move the pointer over the bottom left corner of the taskbar, click Start, and
then click Hyper-V Manager on the Start screen.
2. In Hyper-V Manager, click 10961A-LON-DC1, and in the Actions pane, click Start.
3. In the Actions pane, click Connect. Wait until the virtual machine starts.
o Password: Pa$$w0rd
o Domain: ADATUM
2. Locate a module on LON-DC1 that can work with Server Message Blocks (SMB) shares.
3. Import the module to your local computer, adding the prefix DC to the nouns for each imported
command.
Results: After completing this exercise, you will have used implicit remoting to import and run commands
from a remote computer.
3. Create and display an HTML report that displays local disk information from two computers. Your
report must include each computer’s name, each drive’s letter, and each drive’s free space and total
size in bytes.
2. Create remoting sessions to LON-CL1 and LON-DC1 and save both session objects in the variable
$computers.
Task 2: Create a report that displays Windows Firewall rules from two computers
1. Discover a Windows PowerShell module capable of working with Network Security.
2. Use a single command line to load the module into memory on LON-CL1 and on LON-DC1.
3. Discover a command that can display Windows Firewall rules.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 09-25
4. Use a single command line to list all enabled firewall rules on LON-CL1 and LON-DC1. Display only
the rule names and the computer name each rule came from.
5. Use a single command line to unload the network security module from memory on LON-CL1 and
LON-DC1.
Task 3: Create and display an HTML report that displays local disk information from
two computers. Your report must include each computer’s name, each drive’s letter, and
each drive’s free space and total size in bytes.
1. As a test, use Get-WmiObject to display a list of local hard drives (the Win32_LogicalDisk class,
filtered to include only those drives with a drive type of 3).
2. Use remoting to run the Get-WmiObject command against LON-DC1 and LON-CL1. Do not add a –
ComputerName parameter to the Get-WmiObject command.
3. Revise your command from the previous step to produce the desired HTML report.
Results: After completing this exercise, you will have performed several management tasks against
multiple computers.
Lesson 4
Using Remoting for Delegated Administration
In this lesson, you will learn about another use for remoting: setting up delegated administration. With
the techniques that you will learn, you can set up constrained endpoints that contain a limited set of
commands, allow only a limited set of user accounts, and run commands under an alternative set of
credentials.
Lesson Objectives
After completing this lesson, students will be able to:
• –LanguageMode defines the Windows PowerShell language restrictions. “FullLanguage” enables all
Windows PowerShell language elements; “NoLanguage” turns off script blocks, variables, operators,
and so on; and “RestrictedLanguage” enables only basic comparison operators.
• –ModulesToImport defines a list of modules to load into the session when someone connects.
• –SessionType defines the kind of session. “Empty” means no modules are loaded by default;
“Default” is a normal Windows PowerShell session that includes the Microsoft.Windows
PowerShell.Core snap-in, and “RestrictedRemoteServer” includes only a short selection of
commands such as Get-Help and Get-Command.
• –VisibleAliases, -VisibleCmdlets, and –VisibleFunctions define a list of aliases, cmdlets, and
functions, respectively that will be available. When you use these, any aliases, cmdlets, or functions
not specified are hidden, even if they are loaded into the session.
There are other parameters, and you should review the Help for New-PSSessionConfigurationFile to
learn about its other options and capabilities.
Note: Although you can restrict the commands that are available in a session, you cannot
modify those commands’ parameters. In other words, when a command is included, all of it is
included, not just a piece. If you must provide a version of a command that omits certain
parameters (such as hard-coding a server name instead of allowing one to be specified), you
would create and include a proxy function.
Be careful when locking down an endpoint. For example, if you forget to include Exit-PSSession,
someone connecting with Enter-PSSession will be unable to cleanly exit the session, and will instead be
forced to close their Windows PowerShell window to disconnect.
MCT USE ONLY. STUDENT USE PROHIBITED
09-28 Administering Remote Computers
• –Name specifies the name of the new endpoint. This must be unique on the computer, and you
should consider using your organization name as a kind of namespace to help guarantee uniqueness.
For example, “Adatum.HelpDeskPasswords” is a good endpoint name.
• –RunAsCredential lets you specify the user name (you will be prompted for the password) that will
be used to run all commands within the session. If you omit this parameter, the delegated credential
of the connecting user will be used instead.
• –ShowSecurityDescriptorUI displays a graphical dialog box where you can set the permissions for
the endpoint that is, who may connect to it. You can also use –SecurityDescriptorSDDL and pass a
Security Descriptor Definition Language (SDDL) string. But those strings are fairly complex, and you
may find the dialog box to be easier to work with.
Other parameters overlap functionality with New-PSSessionConfigurationFile, and if you use them, they
will override whatever was specified in the session configuration file. Review the Help for Register-
PSSessionConfiguration to learn more about its other options and capabilities.
Question: Why might you want to save the .pssc files that contain session configuration
information?
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 09-29
Objectives
After completing this lab, students will be able to:
Lab Setup
Estimated Time: 45 minutes
Password: Pa$$w0rd
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must
follow these steps:
1. On the host computer, move the pointer over the bottom left corner of the taskbar, click Start, and
then click Hyper-V Manager on the Start screen.
2. In Hyper-V Manager, click 10961A-LON-DC1, and in the Actions pane, click Start.
3. In the Actions pane, click Connect. Wait until the virtual machine starts.
o Password: Pa$$w0rd
o Domain: ADATUM
6. Start the lab steps on the 10961A-LON-CL1 virtual machine, and also perform exercises 3 and 4 on
10961A-LON-DC1. This will be called out in the individual exercises, so ensure you read the exercise
scenarios prior to commencing the lab exercises.
3. Review the examples in the Help file for the command that can set passwords, to obtain an example
of how to do this.
Results: After completing this exercise, you will have discovered the commands needed to perform the
remaining tasks in this lab.
Task 1: Use Windows PowerShell to create an Active Directory user and group
1. Run a Windows PowerShell command that creates a new Domain Global security group named
HelpDesk. The group should use the samAccountName HelpDesk, and should not at first contain
any members. Allow the group to be created in the default container.
2. Create a new domain user named HelpDeskTest, by using the samAccountName HelpDeskTest.
Create the account in the default container.
Results: After completing this exercise, you will have created a user group that represents the Help Desk
personnel, and added a new user account to that group for testing.
2. If you have not already accomplished this on LON-DC1, open Windows PowerShell.
3. Create a custom session configuration file that is named C:\HelpDesk.pssc, by using the criteria
outlined in the exercise scenario.
Results: After completing this exercise, you will have created a custom session configuration file.
• The session will use a RunAs credential of ADATUM\Administrator, with the password Pa$$w0rd.
• The session will allow only Administrators and members of the HelpDesk user group to connect.
Administrators should be given Full Control over the session configuration, and members of HelpDesk
should be given Full Control permissions.
You will perform this task on LON-DC1.
Results: After completing this exercise, you will have registered your custom session configuration.
Notice that command and parameter tab completion may not work.
7. Try to view the help for the Set-ADAccountPassword cmdlet using different methods - You will
receive an error.
2. In the Virtual Machines list, right click 10961A-LON-DC1, and then click Revert.
Results: After completing this exercise, you will have tested your custom session configuration.
Always consider the security implications of opening remoting too much. The default
configuration is tightly locked down and provides a good balance of ease-of-use and
security/privacy; make sure that, before changing that default configuration, you have explored
all the possible ramifications.
There is also misplaced concern over the CredSSP protocol, that Microsoft describes as an increased
security risk because it enables the delegation of credentials to remote computers, and if those computers
are compromised then the credential could also be compromised. The key phrase is “if those computers
are compromised,” reinforcing the fact that only trusted, managed, secured computers should be enabled
for CredSSP delegation. This concern is why delegating to a wildcard character such as * is incorrect doing
this would allow delegation to any computer. This includes untrusted, unmanaged, unsecured
computers and that is where the security risk lies.
MCT USE ONLY. STUDENT USE PROHIBITED
Administering Remote Computers
09-34
MCT USE ONLY. STUDENT USE PROHIBITED
10-1
Module10
Putting it All Together
Contents:
Module Overview 10-1
Module Overview
In this module, you will complete a real-world task from scratch: performing the initial provisioning of a
newly installed Microsoft Windows Server® 2012 Server Core instance. You will break this task down into
several discrete subtasks, and perform each one individually at the command prompt. After completing
each task at the command prompt, you will add that task’s commands to a script, creating an automated
provisioning process.
Additional Reading: Although you do not need to know any details about Server Core to
complete this module, you can learn more about it at http://technet.microsoft.com/en-
us/library/cc753802%28WS.10%29.aspx.
Objectives
In the module, you will:
• Discover, test, and execute new commands that help complete individual tasks in a larger overall
process
MCT USE ONLY. STUDENT USE PROHIBITED
10-2 Putting it All Together
Lesson 1
Provisioning a New Server Core Instance
In this lesson, you will review the process that you must complete, and break the process down into
individual tasks. Your instructor will briefly review these tasks but will not provide much guidance. You
should refer back to the lesson content as you work on the lab if you want reminders or reference
materials.
Lesson Objectives
After completing this lesson, students will be able to:
• Describe the requirements and criteria of the process that you will automate
Overall Process
The overall process that you will automate is the
core provisioning of a Server Core computer that
is running Microsoft® Windows Server® 2012. The
computer has the operating system installed, and
a local Administrator password is set. Everything
else must be automated by a script that you will
write.
• The credentials that are used to access the computer and the domain
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 10-3
In a production environment, you might perform additional tasks when provisioning a new server, and
you might have to parameterize some of that information.
You should be aware that, in a well-designed environment, many secondary provisioning tasks would be
performed by another method. For example, software would be deployed through Microsoft System
Center 2012 Configuration Manager or by Group Policy Objects (GPOs). Configuration settings would be
pushed out through Group Policy objects. Other provisioning tasks might be performed by other
infrastructure components. For this reason, this module will focus only on the initial provisioning tasks
that cannot be performed by these other common methodologies and technologies.
Your lab environment includes a Microsoft DHCP Server on the LON-DC1 computer. Your LON-CL1 client
computer includes the Remote Server Administration Tools (RSAT) and includes Windows PowerShell™
commands that can query and manage the DHCP Server service on LON-DC1.
You have to discover commands that can list existing DHCP leases. Because a DHCP server can host
multiple address scopes, you will also have to find a command that can list the available scopes.
In production networks, it is common for new servers to be temporarily attached to a dedicated network
subnet for provisioning purposes. These subnets are also known as bench networks, lab networks, and
other names. Your lab environment emulates this kind of environment, and so when you discover what
DHCP scope is available for your use, you will hard-code that DHCP scope ID into your script.
You will therefore have to discover a command that enables you to add a DHCP reservation to the DHCP
server that is running on LON-DC1. That command will likely need the DHCP computer name, the DCHP
scope ID in which to create the reservation, the IP address to assign, and the MAC address (also known as
the client ID) that the IP address will be issued to.
As you work, remember that creating the reservation will not automatically cause the server to begin
using it. The server will continue to use its current IP address until that lease is released or must be
renewed, or until the server is restarted. Your script will therefore have to use the appropriate IP address
at the appropriate time when it tries to communicate with the new server.
MCT USE ONLY. STUDENT USE PROHIBITED
10-4 Putting it All Together
A problem with WinRM is that it typically demands mutual authentication between you and the server
that you are connecting to. In a domain environment, this is provided natively by the Active Directory®
Kerberos authentication protocol. Your new Server Core computer, however, has not yet been joined to
the domain. One alternative would be to install a Secure Sockets Layer (SSL) encryption certificate on the
computer, because such a certificate can also provide mutual authentication. However, that installation is
difficult to perform remotely.
A second alternative is to temporarily modify the WinRM TrustedHosts list on the client computer so that
it no longer demands mutual authentication. This would enable you to connect to the Server Core
computer to begin provisioning it. You will want to save any existing TrustedHost list values before
modifying the list, and restore the original list after you have completed the provisioning process.
The TrustedHosts list on your computer can be accessed by using the PSDrive WSMAN. In that drive, you
would navigate to WSMAN:\Localhost\Client to locate the TrustedHosts item. Typically, the Get-
Content and Set-Content commands can be used to modify the contents of the item. Because this item
is security-sensitive, Windows PowerShell prompts you before changing it.
Sending commands to remote computers can be especially difficult when you also have to send variable
information, such as the computer’s new name, or a domain credential, both of which you will have to
send. Remember that variables defined on the client computer have no meaning on the remote
computer, and cannot be included in the –ScriptBlock parameter of Invoke-Command. However, the
Invoke-Command cmdlet provides a specific way to pass variables’ contents from the client computer to
the remote computer. That technique is implemented by the command’s –ArgumentList parameter,
together with a Param() block inside the –ScriptBlock parameter’s value.
After you send the command to the Server Core computer, you will have to disconnect from it (in
anticipation of its restart) and then wait for some time for the restart to be completed. One way of
robustly waiting for the restart to complete is to try to continually reconnect to the remote computer
through Windows PowerShell remoting. A ping is unreliable because the remote computer’s Windows
Firewall does not allow the Internet Control Message Protocol (ICMP) traffic by default. However, to
simplify this lab, you will tell your script to wait for five minutes after telling the remote computer to
restart. That should give the remote computer time to restart and start accepting connections again.
Objectives
After completing this lab, students will be able to:
Lab Setup
Estimated Time: 120 minutes
Password: Pa$$w0rd
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must
follow these steps:
1. On the host computer, hover the mouse pointer over the bottom left corner of the taskbar, click on
the resultant Start menu, and then click Hyper-V Manager on the Start Screen.
2. In Hyper-V® Manager, click 10961A-LON-DC1, and in the Actions pane, click Start.
3. In the Actions pane, click Connect. Wait until the virtual machine starts.
o Password: Pa$$w0rd
o Domain: ADATUM
6. Repeat steps 2 and 3 for 10961A-LON-SVR1, and sign in with the local user name Administrator and
password Pa$$w0rd.
1. In the Script Pane, create a script named Set-ServerCoreInstance.ps1 that uses cmdlet binding and has
a parameter block
2. Add input parameters to the script. Perform this task in the Script Pane
Task 1: In the Script Pane, create a script named Set-ServerCoreInstance.ps1 that uses
cmdlet binding and has a parameter block
1. Ensure you are signed in to the 10961A-LON-CL1 virtual machine as Adatum\Administrator with
password Pa$$w0rd.
Task 2: Add input parameters to the script. Perform this task in the Script Pane
1. In your Set-ServerCoreInstance.ps1 script, add input parameters for the following:
o MACAddress, a single mandatory string.
o LocalCredential, having a default value that is a parenthetical expression that prompts for a
credential object, ensuring that the prompt includes the message “Local Credential.”
o DomainCredential, having a default value that is a parenthetical expression that prompts for a
credential object, ensuring that the prompt includes the message “Domain Credential.”
Results: After completing this exercise, you will have created the beginnings of a parameterized script.
Exercise 2: Get the Dynamic IP Address of the New Server Core Computer
Scenario
In this exercise, you will use the MAC address of the new Server Core virtual machine to retrieve its IP
address from the DHCP server. You will first perform this task interactively in the shell, and then add a
command to your script to perform this same task.
The main tasks for this exercise are as follows:
2. In the Console pane, look up the IP address of the Server Core instance in the DHCP server
2. Run Ipconfig /all and note the 12-character physical address. Make sure that you include the dashes
between each of the 6 address elements. You will need this physical (MAC) address information
throughout this lab, so make sure you write it down clearly, in an easy-to-access location.
4. In the Console pane on LON-CL1, save the MAC address in the variable $MACAddress.
Task 2: In the Console pane, look up the IP address of the Server Core instance in the
DHCP server
1. Ensure you are still logged on to the 10961A-LON-CL1 virtual machine as Adatum\Administrator
with password Pa$$w0rd.
3. Using a keyword such as Lease, discover the command that will query a DHCP lease from the DHCP
server. Read the Help for the command, and notice that it requires you to specify a DHCP scope.
4. Using a keyword such as Scope, discover the command that will list DHCP scopes from the server
LON-DC1.
5. Place the string value LON-DC1 into a variable named $DHCPServerName.
6. Display a list of DHCP scopes on the server LON-DC1. Write down the IP address of the only scope.
8. Display a list of all leases in the only DHCP scope. Use the variables $DHCPServerName and
$ScopeID in your command.
9. Display the IP address of the Server Core instance. The IP address must be displayed as a simple
string, not as a complex, multiple property object. Save the IP address in a string variable named
$OldIPAddress.
You will have to run 3–4 commands in a pipeline to perform this task.
You will need to use the $MACAddress and $OldIPAddress variables that you created in previous
tasks. You will also need to use the $ScopeID and $DHCPServerName variables that you created in
this task.
Use Where-Object to filter the list of leases so that only the lease having the same client ID (MAC
address) as the Server Core instance is produced as output.
Remember that Select-Object has a parameter, -ExpandProperty, that can extract the contents of a
single property from a complex, multiple property object.
You will have to use Select-Object twice. The first time, expand the IP address. Pipe that to Select-
Object again to expand the IPAddressToString property.
10. Place the $OldIPAddress variable inside double quotation marks, and assign the resulting string to
$OldIPAddress. This will convert the IP address to a string object.
11. Create a variable named $NewComputerName that contains the value LON-SVR2.
Note: The existing name of the target computer is LON-SVR1. We will rename it to the name defined
in the variable $NewComputername as part of this process i.e. LON-SVR2.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 10-9
Results: After completing this exercise, you will have written a command to retrieve an IP address from
the DHCP server based on the MAC address of the computer.
2. In the Script Pane, update your script to create the DHCP reservation
2. Using a keyword like Reservation, find the command that will create a new reservation.
4. Run a command that will create a DHCP reservation for the Server Core instance’s physical (MAC)
address. Use the variables $MACAddress, $ScopeID, $DHCPServerName, and $NewIPAddress in
your command.
Note: You can create the DHCP reservation only once. If your command succeeds, move on to the
next task.
Task 2: In the Script Pane, update your script to create the DHCP reservation
1. Add the command from step 3 of the previous task to the end of your script.
Results: After completing this exercise, you will have created a DHCP reservation for the LON-SVR1
computer.
2. In the Console pane, add the Server Core computer's IP address to the TrustedHosts list
MCT USE ONLY. STUDENT USE PROHIBITED
10-10 Putting it All Together
Task 1: Save the TrustedHosts list to a variable. Perform this task in the Console pane
1. Ensure you are still logged on to the 10961A-LON-CL1 virtual machine as Adatum\Administrator
with password Pa$$w0rd.
Task 2: In the Console pane, add the Server Core computer's IP address to the
TrustedHosts list
1. Run the Set-Item command to add the IP address in $OldIPAddress to your TrustedHosts list.
3. Set the TrustedHosts list back to the value stored in $OriginalTrustedHosts and verify the change.
4. At the end of your script, add the command from step 1 of the previous task. This command must
remain the last command in your script. Future additions to your script must be added before this
command.
Results: After completing this exercise, you will have saved your TrustedHosts list, and added the Server
Core computer’s IP address to it.
Task 1: In the Console pane, add a role to the Server Core computer
1. Ensure you are still logged on to the 10961A-LON-CL1 virtual machine as Adatum\Administrator
with password Pa$$w0rd.
2. Using a keyword like feature, find a command that can add a Windows Feature (role) to a computer.
3. Write a command that runs Get-Credential to prompt for a credential, and then stores it in
$LocalCredential. When prompted, provide the user name Administrator and the password
Pa$$w0rd.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 10-11
4. Write a command that uses Invoke-Command to add the Telnet-Client role to the Server Core
instance. Refer to the Server Core instance by using the IP address in $OldIPAddress. Provide the
credential in $LocalCredential.
Results: After completing this exercise, you will have added a role to the Server Core computer.
2. In the Script Pane, update your script to add and rename the computer
2. Using a keyword like computer, find a command that will let you add a computer to a domain.
3. Write a command that runs Get-Credential to prompt for a credential, and stores that credential in
$DomainCredential. When prompted, provide the user name ADATUM\Administrator and the
password Pa$$w0rd.
4. Write a command that uses Invoke-Command to tell the Server Core instance to add itself to the
domain, to rename itself, and to restart itself. You will need to provide the following information to
the command:
Task 2: In the Script Pane, update your script to add and rename the computer
1. Add the command from step 3 of the previous task to your script. The command must be added
before the command that restores the TrustedHosts list.
Results: After completing this exercise, you will have renamed the Server Core computer and added it to
the domain.
2. In the Console pane, run your C:\Scripts\Set-ServerCoreInstance.ps1 script in a way that prevents
Windows PowerShell from prompting you for anything except the two credentials and any
confirmation prompts.
Note: It is expected that the target computer will restart and you will loose your connection. In the
console prompt you will see an error message saying “..Connection Lost..” attempting to reconnect.
3. Use Get-ADComputer to verify that the new computer is in the domain.
2. In the Virtual Machines list, right click 10961A-LON-DC1, and then click Revert.
Results: After completing this exercise, you will have automated the provisioning process and verified the
results.
Question: Why was it necessary to use the param() block and –ArgumentList with Invoke-
Command?
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 10-13
Always try to test commands in the console before adding them to a script. In this manner, you
have to write and debug only one command at a time. This makes it easier to assemble a
working, bug-free script.
Module11
Using Background Jobs and Scheduled Jobs
Contents:
Module Overview 11-1
Module Overview
In this module, you will learn about the job features of Windows PowerShell™. Jobs are an extension point
in Windows PowerShell, meaning there are many different kinds of jobs. Each kind of job can work slightly
differently, and each kind has different capabilities.
Objectives
After completing this module, students will be able to:
Lesson 1
Using Background Jobs
In this lesson, you will learn about three types of jobs. These three jobs form the basis of the Windows
PowerShell job system.
Lesson Objectives
After completing this lesson, students will be able to:
• Start jobs
• Manage jobs
• Remoting jobs use Windows PowerShell remoting to transmit their commands to one or more remote
computers. The commands are run on those remote computers, and the results are returned to the
local computer and stored in memory. This kind of job requires that Windows PowerShell remoting
be enabled on the remote computers, although in Windows PowerShell version 3.0, you do not need
to enable remoting on the computer where the job is created. Windows PowerShell Help files refer to
this kind of job as a Remote job.
• WMI jobs use Windows Management Instrumentation (WMI). The command runs on your computer
but may connect to one or more remote computers’ WMI services.
Each type of job has different characteristics. For example, local and remoting jobs run in a background
Windows PowerShell runspace. You can think of them as running in a hidden instance of Windows
PowerShell. Other types of jobs may have different characteristics. Also, add-in modules can add more job
types to Windows PowerShell, and those job types will have their own characteristics.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 11-3
Remoting jobs are the most useful for managing multiple remote computers. Because remoting transmits
commands to remote computers, and because the remote computers run those commands by using their
own local resources, nearly any command can be included in the job.
Remember that these are not the only kinds of jobs that Windows PowerShell can contain. Modules and
other add-ins can create additional job types.
Starting Jobs
You start each of the three basic job types in a
different way.
Local Jobs
Start local jobs by running Start-Job. Provide
either the –ScriptBlock parameter to specify a
single command line or a small number of
commands. Provide the –FilePath parameter to
run an entire script on a background thread.
Note: At first, job ID numbers may not seem to be sequential. You will learn why later in
this module.
You can specify the –Credential parameter to have the job run under a different user account. Other
parameters allow you to run the command under a specific Windows PowerShell version, in a 32-bit
session, and so on.
Some examples:
Remoting Jobs
Start remoting jobs by running Invoke-Command. This is the same command you would use to send
commands to a remote computer, and you learned about this command in Module 9, “Administering
Remote Computers.” Add the –AsJob parameter to make the command run in the background, and use
the –JobName parameter to specify a custom job name. All other parameters of Invoke-Command are
used in the same way. For example:
Remoting jobs are created and managed by the computer where Invoke-Command is run. You can refer
to that computer as the initiating computer. The commands inside the job are transmitted to remote
computers. The remote computers execute the job and return the results to the initiating computer. The
initiating computer stores the results of the job in its memory.
WMI Jobs
Start a WMI job by running Get-WmiObject. This is the same command you would use to query WMI
instances from a remote computer, and you learned about this command in Module 6, “Querying
Management Information by Using WMI and CIM.” Add the –AsJob parameter to have the command run
on a background thread. There is no way to provide a custom job name. The Help file for Get-
WmiObject states the following for the –AsJob parameter:
Note: To use this parameter with remote computers, the local and remote computers
must be configured for remoting. Additionally, you must start Windows PowerShell by
using the "Run as administrator" option in Windows Vista and later versions of
Windows. For more information, see about_Remote_Requirements.
However, the Help file is not entirely correct about this behavior. WMI jobs do not require remoting to be
enabled on either the initiating computer or on the remote computer. WMI jobs do require that WMI be
accessible on the remote computers.
Here is an example:
Job Objects
Notice that each of the preceding examples produces a job object as their result. The job object represents
the running job, and can be used to monitor and manage the job.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 11-5
Managing Jobs
When you start a job, you are given a job object.
That object can be used to monitor and manage
the job.
Job Objects
Each job consists of at least two job objects. The
parent job is the top-level object, and represents
the entire job, no matter how many computers
the job connects to. The parent job contains one
or more child jobs. Each child job represents a
single computer. In a local job, there will be only
one child job. Remoting jobs and WMI jobs will
have one child job for each computer that you
specified.
Retrieving Jobs
You can list all current jobs by running Get-Job. You can list a specified job by adding the –ID or –Name
parameter and specifying the desired job ID or job name. Using the job ID, you can also retrieve child
jobs. For example:
PS C:\> Get-Job
Id Name PSJobTypeName State HasMoreData Location
-- ---- ------------- ----- ----------- --------
2 LocalDirectory BackgroundJob Running True localhost
4 TestScript BackgroundJob Completed True localhost
6 RemoteLogs RemoteJob Failed True LON-DC1...
10 Job10 WmiJob Failed False localho...
PS C:\> Get-Job -Name TestScript
Id Name PSJobTypeName State HasMoreData Location
-- ---- ------------- ----- ----------- --------
4 TestScript BackgroundJob Completed True localhost
PS C:\> Get-Job -ID 5
Id Name PSJobTypeName State HasMoreData Location
-- ---- ------------- ----- ----------- --------
5 Job5 Completed True localhost
Notice that each job has a status. Parent jobs always display the status of the worst child job. In other
words, if a parent contains 4 child jobs, and 3 of those jobs finished successfully but 1 of those jobs failed,
the parent job status will be Failed.
This technique enables you to discover the job ID numbers and names of the child job objects. Notice that
child jobs all have a default name that corresponds with their ID number. The preceding syntax will work
in both Windows PowerShell 2.0 and Windows PowerShell 3.0. In Windows PowerShell 3.0, you can also
use the –IncludeChildJobs parameter of Get-Job to display child jobs of a job.
MCT USE ONLY. STUDENT USE PROHIBITED
11-6 Using Background Jobs and Scheduled Jobs
Managing Jobs
Windows PowerShell includes several commands used to manage jobs. Each of these can have one or
more jobs piped to it, or you can specify jobs by using the –ID or –Name parameters. Both of those
parameters accept multiple values, meaning you can specify a comma-separated list of job ID numbers or
names. The job management commands include:
• Stop-Job stops a job that is running. Use this command to cancel a job that is in an infinite loop or
that has run longer than you want.
• Remove-Job deletes a job object, including any command results that were stored in memory. You
should use this when you are finished working with a job so that the shell can free up memory.
• Wait-Job is typically used in a script. It pauses script execution until the specified jobs reach the
specified status. You can use this in a script to start several jobs, and then make the script wait until
those jobs complete before continuing.
Remoting, WMI, and local jobs are managed inside the Windows PowerShell process. When that process
ends, all jobs and their results are removed and can no longer be accessed.
PS C:\> Get-Job
Id Name PSJobTypeName
State HasMoreData Location
-- ---- -------------
----- ----------- --------
13 Job13 BackgroundJob Running True localhost
In this example, job ID 13 is still running, but the HasMoreData column indicates that results have already
been stored in memory.
By default, job results are not stored in memory after they are delivered to you. That means you can use
Receive-Job only once per command. Add the –Keep parameter to retain a copy of the job results in
memory so that you can retrieve them again.
If you retrieve the results of a parent job, you will receive the results from all of its child jobs. You can also
retrieve the results of a single child job, or of multiple child jobs, if needed.
You can retrieve the results of a job that is still running. However, unless you specify –Keep, the job
object’s results will be empty until the job’s command adds new output.
For example:
Demonstration Steps
1. Enable remoting on LON-CL1.
2. Start a local job that produces a complete directory listing for C:\, including subfolders. Give the job
the name LocalDir.
3. Start a remoting job that queries the most recent 100 entries from the Security event log on LON-CL1
and on LON-DC1. Give the job the name RemoteLogs.
8. Display a list of running jobs, and repeat this step every few minutes until the RemoteLogs job
completes.
10. Retrieve the results from LON-DC1, keeping a copy of the results in memory.
11. Retrieve the results from the RemoteLogs parent job.
Question: What are some tasks that you might want to run in the background?
MCT USE ONLY. STUDENT USE PROHIBITED
11-8 Using Background Jobs and Scheduled Jobs
Objectives
After completing this lab, students will be able to:
• Start jobs
• Manage jobs
Lab Setup
Estimated Time: 30 minutes
Password: Pa$$w0rd
The changes you make during this lab will be lost if you revert your virtual machines at another time
during class.
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must
complete the following steps:
1. On the host computer, move the pointer over the bottom left corner of the taskbar, click Start, and
then click Hyper-V Manager on the Start screen.
2. In Hyper-V® Manager, click 10961A-LON-DC1, and in the Actions pane, click Start.
3. In the Actions pane, click Connect. Wait until the virtual machine starts.
o Password: Pa$$w0rd
o Domain: ADATUM
3. Start a remoting job that retrieves a list of physical network adapters from LON-DC1 and LON-CL1.
Name the job RemoteNetAdapt.
4. Start a remoting job that retrieves a list of Server Message Block (SMB) shares from LON-DC1 and
LON-CL1. Name the job RemoteShares.
5. Start a remoting job that retrieves all instances of the Win32_Volume CIM class from every computer
in Active Directory® Domain Services. Name the job RemoteDisks. Because some domain computers
may not be started, some child jobs may fail.
2. Using the range operator (..) and ForEach-Object, start a local job that produces 100 directory
listings of drive C, including subfolders. Name the job LocalDir. Proceed to the next task while this
job is still running.
Results: After completing this exercise, you will have started jobs using two of the basic job types.
2. Stop a Job
You will need to start by querying the parent job, and then expanding its ChildJobs property. Filter
the child jobs so that just the LON-DC1 job remains, and then receive the results form that job. You
will use a total of four commands to complete this step.
Results: After completing this exercise, you will have managed the jobs that you created in the previous
exercise.
MCT USE ONLY. STUDENT USE PROHIBITED
11-10 Using Background Jobs and Scheduled Jobs
Question: Get-CIMInstance does not have an –AsJob parameter. Why? How would you use
it in a job?
Question: What are some potential performance concerns about background jobs?
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 11-11
Lesson 2
Using Scheduled Jobs
In this lesson, you will learn to use scheduled jobs. Scheduled jobs are a new type of job that was
introduced in Windows PowerShell 3.0.
Lesson Objectives
After completing this lesson, students will be able to:
Scheduled jobs are a combination of Windows PowerShell background jobs and Windows® Task
Scheduler tasks. Like background jobs, you define scheduled jobs in Windows PowerShell. Like tasks, job
results are saved to disk, and tasks can run even if Windows PowerShell is not running.
The jobs you will create in this module can be managed by Windows PowerShell and seen in the Windows
Task Scheduler. However, the commands you will learn in this module cannot manage other tasks that
may appear in Windows Task Scheduler.
MCT USE ONLY. STUDENT USE PROHIBITED
11-12 Using Background Jobs and Scheduled Jobs
Note: The ScheduledTasks module includes commands that can manage all tasks in the
Windows Task Scheduler. This module is included with Windows 8 and Windows Server 2012.
You will not learn about this module in this course.
Job Options
Use New-ScheduledJobOption to create a new
job option object. This command has several
parameters that let you define options for the job.
Some of those options include the following:
• –WakeToRun will wake the computer when the job is scheduled to run.
Other parameters allow you to configure jobs that run when the computer is idle, and to configure other
options. Many of the parameters correspond to options in the Windows Task Scheduler GUI.
You do not need to create an option object if you do not want to specify any of its configuration items.
Job Triggers
A job trigger defines when a job will run. Each job
can have multiple triggers. You create a trigger
object by using the New-JobTrigger command.
There are five basic types of trigger:
• –Daily specifies a job that runs every day. You must specify –At and provide a time when the job will
run. You can also specify a –RandomDelay.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 11-13
• –AtLogOn specifies a job that runs when the user logs on. This kind of job is similar to a logon script,
except that it is defined locally rather than in the domain. You can specify –User to limit the user
accounts that trigger the job, and –RandomDelay to add a random delay.
• –AtStartUp is similar to –AtLogOn, except that it runs the job when the computer starts. That
typically runs the job before a user has an opportunity to log on.
For example, this command creates a trigger that runs on Mondays and Thursdays every week, at 3:00
P.M. local time:
• –InitializationScript accepts an optional script block. The command or commands in that script
block will execute before the job starts.
• –MaxResultCount is optional, and specifies the maximum number of result sets to store on disk.
After this number is reached, the shell will delete older result sets to make room for new ones.
To register a new job by using an option object in $opt and a trigger object in $trigger:
The resulting job is registered in the Windows Task Scheduler, and the job definition is created on disk.
Job definitions are XML files stored in your profile folder, under
\AppData\Local\Microsoft\Windows\PowerShell\ScheduledJobs.
You can run Get-ScheduledJob to see a list of scheduled jobs on the local computer. If you know a
scheduled job’s name, you can use Get-JobTrigger and the –Name parameter to retrieve a list of that
job’s triggers.
MCT USE ONLY. STUDENT USE PROHIBITED
11-14 Using Background Jobs and Scheduled Jobs
For example:
PS C:\> Get-Job
Id Name PSJobTypeName State HasMoreData Location Command
-- ---- ------------- ----- ----------- -------- -------
6 LocalDir PSScheduledJob Completed True localhost Dir C:\
You can then use Receive-Job to receive the results of a scheduled job. If you do not specify –Keep, you
can receive the results of a job only once per Windows PowerShell session. However, because the results
are stored on disk, you can open a new Windows PowerShell session and receive the results again. For
example:
Each time the scheduled job runs, a new job object will be created to represent the results of the most
recent job execution. You can use Remove-Job to remove a job. Doing so deletes the results file from
disk. For example:
Demonstration Steps
1. Import the PSScheduledJob module.
3. Create a job trigger that will run a job once in 2 minutes. Store the trigger in the variable $trigger.
4. Using $trigger, create a job named DemoJob that retrieves all entries from the Application event log
on the local computer.
5. Display the triggers for the scheduled job. Notice the time that the job is scheduled to run.
6. Wait for the job to run. While waiting for the job to run, display a list of scheduled jobs.
Question: Why might you use Register-ScheduledJob from the PSScheduledJob module
instead of a command in the ScheduledTasks module?
MCT USE ONLY. STUDENT USE PROHIBITED
11-16 Using Background Jobs and Scheduled Jobs
Objectives
After completing this lab, students will be able to:
Lab Setup
Estimated Time: 30 minutes
Password: Pa$$w0rd
The changes you make during this lab will be lost if you revert your virtual machines at another time
during class.
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must
complete the following steps:
1. On the host computer, move the pointer over the bottom left corner of the taskbar, click Start, and
then click Hyper-V Manager on the Start screen.
2. In Hyper-V® Manager, click 10961A-LON-DC1, and in the Actions pane, click Start.
3. In the Actions pane, click Connect. Wait until the virtual machine starts.
o Domain: ADATUM
2. Create a job option object and store it in $option. Configure the job object as follows:
o The job will run once in 10 minutes. Use Get-Date and a method of the resulting DateTime
object to calculate 10 minutes from now.
2. Create a job trigger object and store it in $trigger2. Configure the trigger as follows:
o The job action retrieves all entries from the Security event log.
o The job name is LocalSecurityLog.
2. Using $option and $trigger2 create a new scheduled job having the following attributes:
o The job action retrieves a list of running processes.
3. Display a list of job triggers, including time, for the LocalSecurityLog scheduled job. Write down the
time.
2. In the Virtual Machines list, right-click 10961A-LON-DC1, and then click Revert.
Results: After completing this exercise, you will have created and run a scheduled job, and retrieved the
results from the job.
Question: Is it possible to create a scheduled job without creating a job option object?
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 11-19
Review Question(s)
Question: What is the main difference between a background job and a scheduled job?
Module12
Using Profiles and Advanced Windows PowerShell
Techniques
Contents:
Module Overview 12-1
Module Overview
In this module, you will learn about several advanced Windows PowerShell™ techniques and features.
Many of these techniques and features extend functionality that you have learned about in previous
modules. Some of these techniques are new and provide additional capabilities.
You can read more about Windows PowerShell profile scripts at this page:
http://technet.microsoft.com/en-us/library/hh847857.aspx
Objectives
After completing this module, students will be able to:
Lesson 1
Using Advanced Windows PowerShell Techniques
This lesson will focus on string and date manipulation, advanced comparison operators, setting default
parameter values, and running external commands. Although each of these topics is small by itself, they
each provide valuable capabilities that you will use throughout your work with Windows PowerShell.
Lesson Objectives
After completing this lesson, students will be able to:
• Convert date values in Windows Management Instrumentation (WMI) and Common Information
Model (CIM) objects
• Compare objects by using advanced parameters
In these examples, you see how to use several of the methods of a String object.
You can learn more about these and other methods by reading the documentation for the
System.String class at this page:
http://msdn.microsoft.com/en-us/library/system.string(v=vs.100).aspx
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 12-3
Note: Notice that the method name is always followed by parentheses, even when the
method requires no arguments. There is no space between the method name and the
parentheses. Properties, such as Length, do not use parentheses.
Windows PowerShell includes three operators that can be used for string manipulation:
• The –Replace operator searches for all occurrences of a substring and replaces them with another
substring:
• The –Join operator accepts an array of strings, and concatenates them together. Each string is
separated by a specified delimiter:
• The –Split operator is the opposite of –Join. It accepts a delimited string and a delimiter, and returns
an array of strings:
Note: These Windows PowerShell operators provide functionality that overlaps the
functionality of the string type’s methods. You are free to use either operators or methods,
depending upon what you are most comfortable with. Remember that the methods are typically
case-sensitive, whereas these operators are case-insensitive.
Note: Some users will use Get-Content to read a comma-separated values (CSV) file. They
will then use a ForEach loop to enumerate the lines of the file, and use –Split to break each line
into individual columns. That approach is valid, but requires significant manual effort. The
Import-CSV command returns more useful results with much less manual effort.
MCT USE ONLY. STUDENT USE PROHIBITED
12-4 Using Profiles and Advanced Windows PowerShell Techniques
Windows PowerShell also offers a [datetime] type accelerator. If you assign this type to a variable, and
then assign a string value to that variable, the shell will try to interpret the string as a date and create a
System.DateTime object. The resulting object will have all the properties and methods of a DateTime
object. For example:
If you try to use this technique by using a string object that cannot be interpreted as a date or time, you
will receive an error:
The properties and methods of System.DateTime are very useful for manipulating dates. For example, as
shown here, you can calculate dates in the past and in the future by adding days, months, hours,
milliseconds, seconds, and more.
Note: The System.DateTime class includes properties and methods for working with ticks.
A tick represents 100 nanoseconds, or one ten-millionth of a second.
For more information about the System.DateTime class and its properties and methods, read:
http://msdn.microsoft.com/en-us/library/system.datetime(v=vs.100).aspx
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 12-5
Get-CimInstance -ClassName
Win32_OperatingSystem |
Select
@{n='LastStartDate';e={$PSItem.LastBoo
tUpTime.ToShortDateString()}}
However, objects retrieved by using Get-WmiObject expose dates and times in an internal WMI format.
To make those easier to use, Windows PowerShell extends all WMI objects to include a
ConvertToDateTime() method. To duplicate this example by using Get-WmiObject, you would run this
command:
This example uses the WMI object’s ConvertToDateTime() method. The object’s own LastBootUpTime
property is provided as an argument to the method. The resulting System.DateTime object’s
ToShortDateString() method is then used to retrieve the desired date representation.
Advanced Operators
You have already learned about several Windows
PowerShell comparison operators, such as –eq, -
ne, -gt, and so on. In this lesson, you also learned
about string manipulation operators like –replace
and –split.
False
PS C:\> "two" -in $collection
True
PS C:\> "six" -in $collection
False
• –Match is a regular expression operator. It returns True if the specified string matches the specified
regular expression pattern. The operator also populates the built-in $Matches array variable with the
matches strings. Regular expression syntax is beyond the scope of this course, but here is an example:
• –As tries to convert an object to a different object type. If the operator cannot perform the
conversion, it may return an error or an empty value. For example:
Notice in the example for –as that the conversion of a fractional number to an integer produces a result
that has been rounded to the nearest integer.
You can read more about these and other comparison operators by running Help
about_comparison_operators in the shell. For more information about regular expressions, run Help
about_regular_expressions in the shell.
Demonstration Steps
1. Assign the string Windows PowerShell to the variable $x.
14. Using the [datetime] accelerator, store the date 1/1/1999 in the variable $mydate.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 12-7
15. Display the day of the week for the date in $mydate.
16. Using a CIM command and the Win32_OperatingSystem class, display the date that the local
computer last started. Title the column LastStartDate and display the date as a short date string.
17. Using a WMI command and the Win32_OperatingSystem class, display the date that the local
computer last started. Title the column LastStartDate and display the date as a short date string.
19. Using the –contains operator, determine whether $servicenames includes the value WinRM.
20. Using the –in operator, determine whether $servicenames includes the value MSSQLServer.
21. Determine whether the string 192.168.12.15 matches the regular expression
\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}.
$PSDefaultParameterValues = @{"Get-CimInstance:ComputerName"="LON-DC1"}
You are changing the built-in $PSDefaultParameterValues variable. It consists of a hash table, and the
hash table contains key-value pairs. Each pair is separated by a semicolon, although this example includes
only one pair. The key consists of the command name, a colon, and the desired parameter name. The
value is the default value that you want to assign. The syntax shown here completely replaces the existing
contents of $PSDefaultParameterValues.
To add a new parameter to the existing variable, use this syntax:
$PSDefaultParameterValues.Add("Get-CimInstance:ClassName","Win32_BIOS")
Again, you are providing a key/value pair to add to the hash table. However, the value and the key are
specified as arguments to the Add() parameter. They are separated by a comma, not by an equal sign.
PS C:\> $PSDefaultParameterValues
Name Value
---- -----
Get-CimInstance:ComputerName LON-DC1
Get-CimInstance:ClassName Win32_BIOS
With the default settings, you can run the command and not provide those parameters:
MCT USE ONLY. STUDENT USE PROHIBITED
12-8 Using Profiles and Advanced Windows PowerShell Techniques
PS C:\> Get-CimInstance
SMBIOSBIOSVersion : 6.00
Manufacturer : Phoenix Technologies LTD
Name : PhoenixBIOS 4.0 Release 6.0
SerialNumber : 8f f8 9a 17 29 b2 98
Version : INTEL - 6040000
PSComputerName : LON-DC1
Notice that the computer name queried, and the class queried, are the ones specified in the default
settings. Those defaults can be overridden:
PS C:\> $PSDefaultParameterValues.Remove("Get-CimInstance:ClassName")
PS C:\> $PSDefaultParameterValues
Name Value
---- -----
Get-CimInstance:ComputerName LON-DC1
As with any variable, the contents of $PSDefaultParameterValues is empty for each new Windows
PowerShell session that you open.
You can read more about this technique by running Help about_parameters_default_values in the shell.
Demonstration Steps
1. Create a default for the –ComputerName parameter of Get-CimInstance, by using the value LON-
DC1.
2. Add a default for the –ClassName parameter of Get-CimInstance by using the value Win32_BIOS.
3. Display the current default parameter values.
Note: You will need remoting enabled for this to succeed if it is not already
This technique works well for external commands that do not have a very complex command-line syntax.
For more complex commands, Windows PowerShell may not correctly interpret the command and its
arguments or parameters. In those cases, the command does not run correctly. This frequently happens
when the command’s syntax includes characters that have special meaning to Windows PowerShell. For
example, the following command will not run correctly from inside Windows PowerShell:
Windows PowerShell 3.0 introduces a new syntax that lets you run commands such as this without error.
Type the command name as usual, but precede its arguments by using --%. Windows PowerShell will not
try to interpret anything after --% and will instead pass it along as-is to Cmd.exe. For example:
Remember that the --% operator is not available in earlier versions of Windows PowerShell. Also
remember that after you use --%, Windows PowerShell will not examine the rest of the command.
Variables, expressions, and other Windows PowerShell features will not be available. More details are
available in help_about_parsing.
MCT USE ONLY. STUDENT USE PROHIBITED
12-10 Using Profiles and Advanced Windows PowerShell Techniques
Lesson 2
Creating Profile Scripts
In this lesson, you will learn about profile scripts. Profile scripts are a Windows PowerShell feature that
enables you to specify a list of commands to run every time that you open a new shell session.
Lesson Objectives
After completing this lesson, students will be able to:
Profile scripts may contain any commands that you want. They are typically used to load modules, define
aliases and variables, and perform other tasks that create a predefined shell environment. By using a
profile script, you can make sure that your shell environment is always configured the way that you want
it, every time you open a new session.
Note: When you connect to a remote computer by using Windows PowerShell remoting,
no profile script is run by default on the remote computer.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 12-11
Profile
Script Console host application ISE host application
Purpose
As shown in this table, some profile scripts are shared by the console host and the ISE host. Other profile
scripts are unique to each host. Some profile scripts are run for every user on the computer, but other
profile scripts are unique to each user on the computer.
Best Practice: If your goal is to have a consistent experience between both host
applications, you should use $home\Documents\WindowsPowerShell\profile.ps1.
MCT USE ONLY. STUDENT USE PROHIBITED
12-12 Using Profiles and Advanced Windows PowerShell Techniques
It is not the goal of Windows PowerShell to act as antimalware software. When malware is present on your
computer, that malware can perform any number of dangerous tasks without using Windows PowerShell
at all. However, the unique behavior of Windows PowerShell profile scripts makes them an attractive
target.
There are two techniques that you can use to prevent your profile script from being used by malware:.
• Always have up-to-date antimalware software installed. The best defense against malware is to keep
it off your computer completely.
• Use the AllSigned Windows PowerShell execution policy, especially on computers that are used by
administrators. Using this execution policy means that your script files, even your profile scripts, will
have to be digitally signed. If a piece of malware changes a signed profile script, the signature on the
script will be broken, and Windows PowerShell will display an error instead of running the script.
Remember that your first security goal should be to keep malware off your computer completely. If your
environment is free of malware, your profile scripts do not represent any security risk. In organizations
that practice extensive defense-in-depth techniques, the AllSigned execution policy is a small additional
layer of security that adds more inconvenience to administrators, because the policy requires all scripts to
be signed before they will run.
Another technique is available that can prevent profile scripts form becoming a risk. This technique is one
that many organizations already use. In this technique, you log on to your computer by using a non-
elevated user account. That account will have its own profile scripts, and you can leave those blank. When
you run Windows PowerShell, open it by using a completely different user account that has elevated
credentials. For example, you might log on to your computer as JeffP. When you run Windows
PowerShell, you run it by using the user account AdminJeffP. The AdminJeffP account has a completely
different set of profile scripts in completely different locations. Those scripts are unavailable to the non-
elevated JeffP account, and so malware running as JeffP would be unable to insert commands into the
profile scripts that are used by AdminJeffP. This approach provides good security, and does not create the
inconvenience of the AllSigned execution policy. However, you should still try to keep malware out of
your environment by using up-to-date anti-malware software.
Demonstration Steps
1. Open the Windows PowerShell ISE.
Lesson 3
Working with Alternative Credentials
In this lesson, you will learn how to create and use reusable objects for alternative credentials. Many
Windows PowerShell commands accept alternative credentials, especially when you connect to remote
computers. Reusable credential objects make it easier to specify a credential for multiple commands.
Lesson Objectives
After completing this lesson, students will be able to:
What Is a Credential?
Many Windows PowerShell commands accept
alternative credentials. That means these
commands enable you to specify a credential
other than the one that you used to open the
Windows PowerShell session. Alternative
credentials are typically used when you connect to
a remote computer, when your local credentials
do not have permission to complete a particular
task on the remote computer. Commands that
accept alternative credentials do so by using a –
Credential parameter.
The easiest way to specify an alternative credential
is to provide a user name, or a domain name and user name, to the –Credential parameter. For example:
When you specify a user name, Windows PowerShell uses a graphical dialog box to prompt you for the
account password. You cannot directly specify the password on the command-line. Doing this would let
you list a password in clear text, and that would be a security issue.
If you have to use the same credential multiple times, having to repeatedly type the same password can
be time-consuming, error-prone, and not what you want. Therefore, the shell also lets you create a
reusable credential object that contains both the user name and an encrypted password.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 12-15
The Get-Credential command displays a dialog box to collect the user name and password.
Note: The Get-Credential command does not validate the credential you provide. The
credential is not validated until you attempt to use it as part of another command.
As with all variables, $cred in this example will exist only until the shell session closed. If you have a
credential that you use regularly, consider adding the Get-Credential command to a profile script. If you
do this, you are prompted for the credential every time that a new shell window opens, and the credential
variable will be available for use during that shell session.
MCT USE ONLY. STUDENT USE PROHIBITED
12-16 Using Profiles and Advanced Windows PowerShell Techniques
Persisting Credentials
Many Windows PowerShell users ask whether you
can save a credential object to disk. They typically
have a goal of using a credential without being
prompted for its password. There are many ways
to achieve this goal. However, they all include
significant security risks.
This command will then read the password from the file, and create a new credential object that uses the
password:
The problem with this approach, and with other similar approaches, is that anyone could read the
password from the text file and create the same credential object. Although the file has no reference to
the user account that the password is for, the password is nevertheless not stored in a secure manner.
As a best practice, you should avoid storing a password to disk under any circumstances, for the same
reasons that you should avoid writing a password down on a piece of paper and attaching it to your
computer monitor. Stored passwords are too easily discovered and compromised.
Demonstration Steps
1. Create a credential object for ADATUM\Administrator. Store the credential in the variable $cred.
2. Use the credential object to query the 10 newest Security event log entries from LON-DC1.
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 12-17
Objectives
After completing this lab, students will be able to:
Lab Setup
Estimated Time: 75 minutes
Virtual Machines: 10961A-LON-DC1, 10961A-LON-CL1
Password: Pa$$w0rd
The changes that you make during this lab will be lost if you revert your virtual machines at another time
during class.
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must
follow these steps:
1. On the host computer, move the pointer over the bottom left corner of the taskbar, click Start, and
then click Hyper-V Manager on the Start screen.
2. In Hyper-V® Manager, click 10961A-LON-DC1, and in the Actions pane, click Start.
3. In the Actions pane, click Connect. Wait until the virtual machine starts.
o Password: Pa$$w0rd
o Domain: ADATUM
. E:\Mod12\Labfiles\Lab12.ps1
Notice that there are a period and a space before the E:\ in the file name you may also need to
modify the execution policy depending on your setting.
The script that you ran in step 1 created several variables and populated them with data. You will use
those variables to answer several questions and to perform several tasks.
For each of the following, write a single command that will answer the question or perform the task:
6. Produce a comma-separated string that contains the values in the array $ComputerNames.
8. In the variable $Phrase, replace the word dog with the word gelding.
9. $List contains a comma-separated list. Display the second value in this list.
The script that you ran in step 1 created several variables and populated them with data. You will use
those variables to answer several questions and to perform several tasks.
For each of the following, write a single command that will complete the task:
4. In $phrase, replace the value over with the value around, and display an all-uppercase version of the
result.
6. Display the contents of $padded so that there are no additional spaces before or after value.
8. Display True or False, depending on whether the contents of $phrase starts with the value The.
9. Display the contents of $unpadded so that 10 additional spaces are added before value.
For each of the following, write a single command that uses $today to complete the task:
Results: After completing this exercise, you will have practice with using several Windows PowerShell
techniques.
Results: After completing this exercise, you will have practiced how to use alternative credentials.
4. In the new script, add a command that creates a new credential object for ADATUM\Administrator,
storing the credential in $cred.
5. Save the script as the current-user, all-hosts profile script.
MCT USE ONLY. STUDENT USE PROHIBITED
12-20 Using Profiles and Advanced Windows PowerShell Techniques
o Command: Get-EventLog
o Parameter: –LogName
o Value: Security
o Command: Get-EventLog
o Parameter: –Newest
o Value: 10
2. In the Virtual Machines list, right click 10961A-LON-DC1, and then click Revert.
3. In the Revert Virtual Machine dialog box, click Revert.
Results: After completing this exercise, you will have created a profile script.
Question: If your user profile is redirected to a network location, will profile scripts still work?
Question: How can you quickly obtain a list of methods and properties for a string object or
for a date object?
MCT USE ONLY. STUDENT USE PROHIBITED
Automating Administration with Windows PowerShell 12-21
Course Evaluation
Your evaluation of this course will help Microsoft
understand the quality of your learning experience.
4. Make sure that the icon caption says Windows PowerShell and that it does not say Windows
PowerShell (x86). Right-click the icon, and then click Run as Administrator.
5. Make sure that the window title bar says Administrator and does not include the text (x86). This
indicates that it is the 64-bit console application and it is being run as Administrator.
6. On the taskbar, right-click the Windows PowerShell icon and then click Pin to taskbar. 64-bit
Windows PowerShell should now be open, running as Administrator, and available on the taskbar for
future use.
b. Click Properties.
c. In the ‘‘Windows PowerShell Properties’’ dialog box on the Font tab, select Consolas. Select a
font size that is comfortable to read.
a. On the Colors tab, review the available foreground (text) and background colors.
a. On the Layout tab, in the Window Size settings, change the area’s Width and Height values
until the Windows PowerShell console pane preview fits completely within the Window Preview
area.
b. On the Layout tab in the Screen Buffer Size settings, change the Width value to be the same as
the Windows Size settings Width value.
4. Click OK. The console application should now be ready for use.
Start-Transcript C:\DayOne.txt
You have now started a transcript, and it will save all of your commands and command output until
you run Stop-Transcript or until you close the shell window.
2. You can view all the commands you have run and the command output by opening the file
C:\DayOne.txt.
MCT USE ONLY. STUDENT USE PROHIBITED
L01-2 Automating Administration with Windows PowerShell
Results: After completing this lab, you will have opened and configured the Windows PowerShell console
application and configured its appearance and layout.
MCT USE ONLY. STUDENT USE PROHIBITED
L01-3
In the Windows PowerShell console application, type ise and then press Enter. Notice that this will work
correctly only when the console is running as Administrator.
or
Right-click the Windows PowerShell icon on the taskbar and then click Run ISE as Administrator.
Task 2: Customize the appearance of the ISE to use the single-pane view, hide the
Command Pane, and adjust the font size
1. To configure the ISE to use a single-pane view:
a. On the Windows PowerShell ISE toolbar, click the Show Script Pane Maximized button (third
from the right).
b. Click the blue Hide Script Pane up-arrow icon on the extreme right side until the console pane is
displayed.
2. Use the Show Command Add-on button (rightmost button on the toolbar) to hide or view the
Command Pane.
3. To adjust the font size, use the slider in the lower-right corner of the window to adjust the font size
until you can read it comfortably.
Results: After completing this lab, you will have customized the appearance of the Windows PowerShell
ISE application.
MCT USE ONLY. STUDENT USE PROHIBITED
L01-4 Automating Administration with Windows PowerShell
2. Run:
help *resolve*
or:
Get-Command *resolve*
These display a list of commands that use Resolve in their names. This should lead you to the
Resolve-DNSName command.
3. Run:
help *adapter*
or:
Get-Command *adapter*
These display a list of commands that use Adapter in their names. This should lead you to the Set-
NetAdapter command. Then, run help set-netadapter to view the Help for that command. This
should lead you to the ---MACAddress parameter.
4. Run:
help *sched*
or:
Get-Command *sched*
These display a list of commands that use Sched in their name. This should lead you to the Enable-
ScheduledTask command (you may also find the Enable-PSScheduledTask command that is
similar).
5. Run:
or:
help *block*
These display a list of commands. This should lead you to the Block-SMBShare command. Then, run
help block-smbshare to learn that the command applies a Deny entry to the file share Discretionary
Access Control List (DACL).
MCT USE ONLY. STUDENT USE PROHIBITED
L01-5
6. Run:
help *branch*
This will cause the Help system to conduct a full-text search, because no commands use branch in
their names. Or, run:
help *cache*
or:
Get-Command *cache*
These will display a list of commands. Either way, you should discover the Clear-BCCache command.
help *firewall*
or
Get-Command *firewall*
or
help *rule*
or
Get-Command *rule*
These display a list of commands that use those keywords in their names. This should lead you to the
Get-NetFirewallRule command
Then, run:
This will display the Help for the command. This should let you discover the ---Enabled parameter.
8. Run:
help *address*
This will display a list of commands that use address in their names. This should lead you to the Get-
NetIPAddress command.
9. Run:
help *suspend*
or:
These display a list of commands. This should lead you to the Suspend-PrintJob command.
10. Run:
MCT USE ONLY. STUDENT USE PROHIBITED
L01-6 Automating Administration with Windows PowerShell
help *format*
or:
These display a list of commands. This should lead you to the Format-Volume command.
Results: After completing this exercise, you will have demonstrated your ability to use the command
discoverability features of Windows PowerShell™ to find new commands that perform specific tasks.
MCT USE ONLY. STUDENT USE PROHIBITED
L01-7
Notice that this command returns only a True or False value, without any other output.
6. To display the newest 10 entries from the Security event log, run:
Results: After completing this exercise, you will have demonstrated your ability to run Windows
PowerShell commands by using correct command-line syntax.
MCT USE ONLY. STUDENT USE PROHIBITED
L01-8 Automating Administration with Windows PowerShell
help *comparison*
then run:
Notice the ---Like operator in about_comparison_operators. To find it, in the Help window’s Find
text box, type wild, and then click Next.
3. After reading the about_comparison_operators Help file, you should learn that typical operators are
not case-sensitive. Specific case-sensitive operators are provided in about_comparison_operators.
$env:computername
5. Run:
help *signing*
then run:
help about_signing
Then read about code signing. You should learn that Makecert.exe is used to create a self-signed
digital certificate.
6. Run:
help *3*
then run:
help about_windows_powershell_3.0
You should learn that there are at least 16 new features in Windows PowerShell 3.0.
2. In the Virtual Machines list, right click 10961A-LON-DC1, and then click Revert.
Results: After completing this exercise, you will have demonstrated your ability to locate Help content in
‘‘About’’ files.
MCT USE ONLY. STUDENT USE PROHIBITED
L01-10
MCT USE ONLY. STUDENT USE PROHIBITED
L02-11
help *date*
Get-Date | Get-Member
help *hotfix*
Get-Hotfix | Get-Member
This will display the properties of the hotfix object. If needed, run Get-Hotfix to see some of the
values that typically appear in those properties.
help *scope*
4. To display a list of scopes that includes only the specified properties, run:
help *rule*
Get-NetFirewallRule
5. To display a list of enabled rules that includes only specified properties, run:
help *neighbor*
Get-NetNeighbor
5. To display a sorted neighbor list that includes only specified properties, run:
ping LON-DC1
ping LON-CL1
help *cache*
Get-DnsClientCache
5. To display the DNS cache and include only specified properties, run:
Results: After completing this exercise, you will have produced several custom reports that contain
management information from your environment.
MCT USE ONLY. STUDENT USE PROHIBITED
L02-14 Automating Administration with Windows PowerShell
Note: In this document, long commands are typically displayed on several lines. Doing so
helps prevent an unintended line break in the middle of a command. However, when you type
these commands, you should type them as a single line. That line may wrap on your screen into
multiple lines, but the command will still work. You should press Enter only after typing the entire
command.
Get-Process
3. To display a list of running processes, sorted in reverse alphabetic order by process name, that shows
only the process name, ID, virtual memory, and physical memory consumption, run:
Get-Process |
Sort Name -Descending |
Select Name,ID,VM,PM
Get-Process |
Sort Name -Descending |
ConvertTo-HTML –Property Name,ID,VM,PM
Get-Process |
Sort Name -Descending | ConvertTo-HTML –Property Name,ID,VM,PM |
Out-File ProcReport.html
Invoke-Expression .\ProcReport.html
Get-Process |
Sort Name -Descending | ConvertTo-HTML –Property Name,ID,VM,PM –PreContent
"Processes" –PostContent (Get-Date) |
Out-File ProcReport.html
Invoke-Expression .\ProcReport.html
MCT USE ONLY. STUDENT USE PROHIBITED
L02-15
Results: After completing this exercise, you will have converted objects to different forms of data.
MCT USE ONLY. STUDENT USE PROHIBITED
L02-16 Automating Administration with Windows PowerShell
Note: When typing these commands, you should type them as a single line, and press
Enter only once, after typing the entire line. However, in the Console application, you can also
type these commands exactly as they are shown. Typically, that means pressing Enter after each
vertical pipe (|) character. If you use this technique, you will have to press Enter on a blank line,
after typing all of the lines, to execute the command.
Notepad SysEvents.csv
5. To export the log and remove the comment line containing type information, run:
Notepad SysEvents.csv
Get-Service |
Sort Status –Descending
Get-Service |
Sort Status –Descending |
Export-CliXML Services.xml
Notepad Services.xml
Get-Service |
MCT USE ONLY. STUDENT USE PROHIBITED
L02-17
Notepad Services.xml
Task 3: Produce a pipe-delimited list of the most recent 20 Security event log entries
1. To view the Help file for ConvertTo-HTML, run:
Notepad Security.pdd
Results: After completing this lab, you will have imported data from and exported data to external
storage.
MCT USE ONLY. STUDENT USE PROHIBITED
L02-18 Automating Administration with Windows PowerShell
help *user*
Notice that the ---Filter parameter is mandatory. Review the examples for the command.
Get-ADUser –Filter *
Task 2: Create a report that shows Security event log entries having the event ID
4624
1. To display a list of Security event log entries that have the event ID 4624, run:
Invoke-Expression .\EventReport.html
3. To show only the certificates that do not have a private key, run either this:
or this:
4. To display the list again by using the specified filtering criteria, run:
5. To display the list again by using the specified filtering criteria and showing only the specified
properties, run:
Task 4: Create a report that shows disk volumes that are running low on space
1. To display a list of disk volumes, run:
Get-Volume
If you did not know the command name, you could have run Help *volume* to discover the
command name.
Get-Volume | Get-Member
3. To display only volumes that have more than zero bytes of free space, run:
Get-Volume |
Where-Object { $PSItem.SizeRemaining -gt 0 }
4. To display only volumes that have less than 99 percent free space, and more than zero bytes of free
space, run:
Get-Volume |
Where-Object { $PSItem.SizeRemaining -gt 0 -and $PSItem.SizeRemaining / $PSItem.Size
-lt .99 }
5. To display only volumes that have less than 10 percent free space and more than zero bytes of free
space, run:
Get-Volume |
MCT USE ONLY. STUDENT USE PROHIBITED
L02-20 Automating Administration with Windows PowerShell
This command may not produce any output on your lab computer if the computer has more than 10
percent free space on all of its volumes.
help *control*
Get-ControlPanelItem
Results: After completing this exercise, you will have used filtering to produce lists of management
information that include only specified data and elements.
MCT USE ONLY. STUDENT USE PROHIBITED
L02-21
help *random*
1..100
1..100 |
ForEach { Get-Random –SetSeed $PSItem }
2. Run:
2. In the Virtual Machines list, right click 10961A-LON-DC1, and then click Revert.
3. In the Revert Virtual Machine dialog box, click Revert.
Results: After completing this exercise, you will have written commands that manipulate multiple objects
in the pipeline.
MCT USE ONLY. STUDENT USE PROHIBITED
L03-23
1. This command is intended to list the services that are running on every computer in the domain:
Get-ADComputer –Filter * |
Get-Service
No. Get-Service does not accept ADComputer objects from the pipeline.
2. This command is intended to list the services that are running on every computer in the domain:
Get-ADComputer –Filter * |
Select @{n='ComputerName';e={$PSItem.Name}} |
Get-Service
3. This command is intended to query an object from every computer in the domain:
Get-ADComputer –Filter * |
Select @{n='ComputerName';e={$PSItem.Name}} |
Get-WmiObject –Class Win32_BIOS
This command is intended to list the services that are running on every computer that is listed in
Names.txt.
Get-Content Names.txt |
Get-Service
This command is intended to list the services that are running on every computer that is listed in
Names.txt.
6. This command is intended to list the services that are running on every computer in the domain:
7. This command is intended to list the Security event log entries from every computer in the domain:
Because Get-EventLog does not accept pipeline input for its ---ComputerName parameter, you have to
write this command:
2. You have a text file that is named Names.txt that contains one computer name per line. Write a
command that uses Restart-Computer to restart each computer that is listed in the file. Do not use a
parenthetical command.
Because the --
-ComputerName parameter of Restart-Computer accepts pipeline input by using
ByValue, the following command will achieve the goal:
Get-Content Names.txt |
Restart-Computer
3. You have a file that is named Names.txt that contains one computer name per line. Write a command
that uses Test-Connection to test the connectivity to each computer that is listed in the file.
The --
-ComputerName parameter of Test-Connection accepts pipeline input only by using
ByPropertyName. The objects produced by Get-Content do not have a property named
MCT USE ONLY. STUDENT USE PROHIBITED
L03-25
ComputerName, nor do they have an existing property that can be renamed to ComputerName.
Therefore, you must use a parenthetical command:
4. Write a command that uses Set-Service to set the start type of the WinRM service to Auto on every
computer in the domain. Do not use a parenthetical command.
Because the --
-ComputerName parameter of Set-Service accepts pipeline input by using
ByPropertyName, you can write the following command:
Get-ADComputer –filter * |
Select-Object {n='ComputerName';e={$PSItem.Name}} |
Set-Service –Name WinRM –StartupType Auto
You must use Select-Object because the ADComputer objects have a Name property, not a
ComputerName property.
Results: After completing this exercise, you will have reviewed and written several Windows PowerShell™
commands.
MCT USE ONLY. STUDENT USE PROHIBITED
L03-26
MCT USE ONLY. STUDENT USE PROHIBITED
L04-27
Notice the ---Name and ---ItemType parameters, and review the command examples.
Results: After completing this exercise, you will have created a new folder on the file system.
MCT USE ONLY. STUDENT USE PROHIBITED
L04-28 Automating Administration with Windows PowerShell
Notice the ---Name, ---Root, and ---PSProvider parameters. Review the command examples.
Results: After completing this exercise, you will have created a new, temporary PSDrive.
MCT USE ONLY. STUDENT USE PROHIBITED
L04-29
Results: After completing this exercise, you will have created a new registry key.
MCT USE ONLY. STUDENT USE PROHIBITED
L04-30 Automating Administration with Windows PowerShell
Results: After completing this exercise, you will have added a new program to the autorun list.
MCT USE ONLY. STUDENT USE PROHIBITED
L04-31
2. In the Virtual Machines list, right click 10961A-LON-DC1, and then click Revert.
3. In the Revert Virtual Machine dialog box, click Revert.
Results: After completing this exercise, you will have modified the maximum number of concurrent
connections for Windows PowerShell remoting.
MCT USE ONLY. STUDENT USE PROHIBITED
L04-32
MCT USE ONLY. STUDENT USE PROHIBITED
L05-33
Computer name
Description
Domain
Manufacturer
Model
Number of processors
Installed physical memory in gigabytes (GB)
Process name
ID
Virtual memory in megabytes (MB) to two decimal places
Physical memory in megabytes (MB) to two decimal places
2. The table should not have additional space between the columns. Redirect the table to a text file that
is named Procs.txt.
Get-Process |
Format-Table –Property Name,ID,@{n='VM(MB)';e={$PSItem.VM /
1MB};formatString='N2'},@{n='PM(MB)';e={$PSItem.PM / 1MB};formatString='N2'} –
AutoSize |
Out-File Procs.txt
2. Destination prefix must be right-aligned. The table must not include additional space between
columns.
3. To create the specified table, run:
Get-NetRoute |
Format-Table -Property AddressFamily,RouteMetric,TypeOfRoute,
@{n='DestinationPrefix';e={$PSItem.DestinationPrefix};align='right'} -AutoSize
Results: After completing this exercise, you will have created various commands that produce formatted
output.
MCT USE ONLY. STUDENT USE PROHIBITED
L05-35
Name Size(KB)
---- --------
explorer.exe 2,324.65
HelpPane.exe 863.00
notepad.exe 238.00
regedit.exe 155.50
splwow64.exe 123.50
bfsvc.exe 73.50
hh.exe 17.00
winhlp32.exe 10.50
write.exe 10.50
2. Display the most recent 20 entries from the Security event log. Calculate the difference between the
time each event was generated and the time that it was written. Display the list exactly as shown here,
with the largest time difference shown first, and the smallest time difference shown last.
EventID TimeDifference
------- --------------
4672 00:00:02
4624 00:00:01
4672 00:00:00
4624 00:00:00
4672 00:00:00
4624 00:00:00
2. In the Virtual Machines list, right click 10961A-LON-DC1, and then click Revert.
Results: After completing this exercise, you will have written commands to reproduce specified output.
MCT USE ONLY. STUDENT USE PROHIBITED
L05-36
MCT USE ONLY. STUDENT USE PROHIBITED
L06-37
Remember that you can run the first command and pipe its output to Get-Member to see what
properties are available.
Format-List –Property *
Remember that Get-Member does not display property values, but Format-List can.
Results: After completing this lab, you will have queried repository classes by using WMI commands.
MCT USE ONLY. STUDENT USE PROHIBITED
L06-39
You should now see a returned list of all domain and local accounts.
Results: After completing this exercise, you will have queried repository classes by using CIM commands.
MCT USE ONLY. STUDENT USE PROHIBITED
L06-41
You should see a prompt in LON-CL1 console saying ReturnValue=0 and PSComputerName
=LON-DC1.
2. Switch to the LON-DC1 virtual machine and you should see it restarting.
5. Check the status of the WinRM service and verify it has changed.
2. In the Virtual Machines list, right click 10961A-LON-DC1, and then click Revert.
Results: After completing this exercise, you will have used CIM and WMI commands to invoke methods of
repository objects.
MCT USE ONLY. STUDENT USE PROHIBITED
L06-42
MCT USE ONLY. STUDENT USE PROHIBITED
L07-43
Get-ExecutionPolicy
C:\Test.ps1
Set-ExecutionPolicy RemoteSigned
2. In the Virtual Machines list, right click 10961A-LON-DC1, and then click Revert.
Results: After completing this exercise, you will have configured and tested the execution policy on a
computer.
MCT USE ONLY. STUDENT USE PROHIBITED
L07-44
MCT USE ONLY. STUDENT USE PROHIBITED
L08-45
2. Run the following command to ensure that the local execution policy is correct:
Set-ExecutionPolicy RemoteSigned
6. Click Run Script in the Windows PowerShell ISE toolbar, or press F5.
Results: After completing this exercise, you will have tested the command and verified its functionality.
MCT USE ONLY. STUDENT USE PROHIBITED
L08-46 Automating Administration with Windows PowerShell
3. Identify two values in this command that might have to change every time someone runs the
command.
4. The ---Filter parameter controls which kinds of logical disks are returned by the command. Local fixed
drives are represented by the ‘‘DriveType=3’’ value. This could be changed to examine removable
drives.
5. The ---ComputerName parameter specifies the computer on which you want to run the CIM
operation controls. The default value is localhost. This value could be changed to examine a different
computer.
2. On the File menu, click Save As to save the empty file as a script.
3. Browse to drive C and save the file as Get-DiskInfo.ps1. If you cannot save the file, the Windows
PowerShell ISE was not opened as Administrator.
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True)]
[string]$ComputerName,
[int]$DriveType = 3
)
This creates a new parameter block that includes the cmdlet binding attribute. The block defines two
parameters and assigns a default value to the second parameter.
1. Close all open files in the ISE. On the File menu, click Open.
6. Press Ctrl+C.
MCT USE ONLY. STUDENT USE PROHIBITED
L08-47
11. In the File name box, type C:\Get-DiskInfo.ps1, and then press Enter.
1. Close all open files in the ISE. On the File menu, click Open.
3. Press F5.
Results: After completing this exercise, you will have identified and parameterized changing values in the
command.
MCT USE ONLY. STUDENT USE PROHIBITED
L08-48 Automating Administration with Windows PowerShell
1. Close all open files in the ISE. On the File menu, click Open.
4. In the File name box, type C:\Get-DiskInfo.ps1, and then press Enter.
1. Close all open files in the ISE. On the File menu, click Open.
4. In the File name box, type C:\Get-DiskInfo.ps1, and then press Enter.
7. At the console prompt, type the following, and then press Enter:
Cd \
8. At the console prompt, type the following, and then press Enter:
9. At the console prompt, type the following, and then press Enter:
Results: After completing this exercise, you will have changed your script so that it produces verbose
output.
MCT USE ONLY. STUDENT USE PROHIBITED
L08-49
1. Close all open files in the ISE. On the File menu, click Open.
4. In the File name box, type C:\Get-DiskInfo.ps1, and then press Enter.
<#
.SYNOPSIS
Retrieves disk space information.
.DESCRIPTION
Retrieves disk information from a single computer.
.PARAMETER ComputerName
The name of the computer to query.
.PARAMETER DriveType
The type of drive to query. Defaults to 3, representing local fixed disks.
.EXAMPLE
.\Get-DiskInfo -ComputerName localhost -Verbose
#>
4. In the File name box, type C:\Get-DiskInfo.ps1, and then press Enter.
7. At the console prompt, type the following, and then press Enter:
Cd \
8. At the console prompt, type the following, and then press Enter:
Results: After completing this exercise, you will have added documentation to your script by using
comment-based help.
MCT USE ONLY. STUDENT USE PROHIBITED
L08-51
Function Get-DiskInfo {
9. In the File name box, type C:\Tools.ps1, and then press Enter. If you are prompted in the Confirm
Save As dialog box, click Yes.
1. Close all open files in the ISE. On the File menu, click Open.
Get-DiskInfo --
-Comp localhost
On the File menu, click Save as.
In the File name box, type C:\Tools.ps1, and then press Enter.
In the Confirm Save As dialog box, click Yes.
1. Close all open files in the ISE. On the File menu, select Open.
2. Navigate to E:\ Mod08\Labfiles\LabB and open Exercise1-Task3.ps1.
MCT USE ONLY. STUDENT USE PROHIBITED
L08-52 Automating Administration with Windows PowerShell
4. In the File name box, type C:\Tools.ps1, and then press Enter.
5. In the Confirm Save As dialog box, click Yes.
6. Press F5.
Results: After completing this exercise, you will have converted the code in your script into a function.
MCT USE ONLY. STUDENT USE PROHIBITED
L08-53
1. Close all open files in the ISE. On the File menu, click Open.
4. In the File name box, type C:\Tools.ps1, and then press Enter.
7. Press Ctrl+S.
1. On the taskbar, click the File Explorer icon to open a new File Explorer window.
3. Type the following and press Enter (because the module may not be loaded, this command may
produce an error that you may ignore):
Remove-Module MyTools
Results: After completing this exercise, you will have saved your script as a script module.
MCT USE ONLY. STUDENT USE PROHIBITED
L08-55
1. Close all open files in the ISE. On the File menu, click Open.
6. Press Ctrl+D.
$ComputerName
Exit
12. Press Y.
Remove-Module MyTools
Results: After completing this exercise, you will have added debugging breakpoints to the MyTools script
module.
MCT USE ONLY. STUDENT USE PROHIBITED
L08-57
Try {
} Catch {
Write-Verbose "Error querying $ComputerName"
}
Remove-Module MyTools
You should recveive verbose output as the script runs, ultimately resulting in an error mesage when
querying BAD, because it doesn’t exist.
10. Type the following to remove the module, and then press Enter:
Remove-Module MyTools
Results: After completing this exercise, you will have added error handling to an existing function.
MCT USE ONLY. STUDENT USE PROHIBITED
L08-59
Try {
} Catch {
Write-Verbose "Failed to connect to $ComputerName"
}
Results: After completing this exercise, you will have added error handling to a function that someone
else wrote.
MCT USE ONLY. STUDENT USE PROHIBITED
L08-60 Automating Administration with Windows PowerShell
Results: After completing this exercise, you will have tested an existing command and identified
changeable values.
MCT USE ONLY. STUDENT USE PROHIBITED
L08-61
1. Close all open files in the ISE. On the File menu of the Windows PowerShell ISE, click Open.
function Get-OSInfo {
}
5. Press Ctrl+A.
6. Press Ctrl+C.
[CmdletBinding()]
param(
[Parameter(Mandatory=$True)]
[string]$ComputerName
)
7. Press Ctrl+S.
MCT USE ONLY. STUDENT USE PROHIBITED
L08-62 Automating Administration with Windows PowerShell
1. Close all open files in the ISE. On the File menu, click Open.
7. Press Ctrl+S.
1. Close all open files in the ISE. On the File menu, click Open.
6. Press Ctrl+D.
7. Type the following and press Enter (if this command produces an error, ignore it):
Remove-Module MyTools
Remove-Module MyTools
Results: After completing this exercise, you will have created a parameterized function by using the
provided command.
MCT USE ONLY. STUDENT USE PROHIBITED
L08-63
1. Close all open files in the ISE. On the File menu, click Open.
[string[]]$ComputerName
7. Press Ctrl+S.
7. Press Tab.
1. Close all open files in the ISE. On the File menu, click Open.
6. Press Ctrl+D.
7. Type the following and press Enter:
Remove-Module MyTools
Results: After completing this exercise, you will have changed a function to accept multiple computer
names as input.
MCT USE ONLY. STUDENT USE PROHIBITED
L08-65
1. Close all open files in the ISE. On the File menu, click Open.
Try {
} Catch {
Write "Error connecting to $name"
}
2. Press Ctrl+S.
1. Close all open files in the ISE. On the File menu, click Open.
Remove-Module MyTools
MCT USE ONLY. STUDENT USE PROHIBITED
L08-66 Automating Administration with Windows PowerShell
2. In the Virtual Machines list, right click 10961A-LON-DC1, and then click Revert.
Results: After completing this exercise, you will have added error handling to a function.
MCT USE ONLY. STUDENT USE PROHIBITED
L09-67
set-executionPolicy RemoteSigned
4. On the LON-CL1 computer, run Enable-PSremoting. Answer Yes to all prompts by entering Y. This
will enable remoting.
help *sessionconfiguration*
Get-PSSessionConfiguration
Results: After completing this exercise, you will have enabled remoting on the client computer.
MCT USE ONLY. STUDENT USE PROHIBITED
L09-68 Automating Administration with Windows PowerShell
3. After you are connected, to install the Network Load Balancing (NLB) feature on LON-DC1, run:
Install-WindowsFeature NLB
5. To disconnect, run:
Exit-PSSession
You should receive an error that is indicative of the second hop. By default, you cannot establish a
connection through an already-established connection.
Exit-PSSession
3. Run:
Notepad
Notice that the shell seems to stop responding while it waits for Notepad to open, because Notepad
is a graphical application and the shell has no way to display the graphical user interface (GUI).
5. To disconnect, run:
Exit-PSSession
MCT USE ONLY. STUDENT USE PROHIBITED
L09-69
Results: After completing this exercise, you will have connected to a remote computer and performed
maintenance tasks on it.
MCT USE ONLY. STUDENT USE PROHIBITED
L09-70 Automating Administration with Windows PowerShell
help *adapter*
help Get-NetAdapter
Get-Process | Get-Member
Notice that the second set of results does not include MemberType of Method, and that the
TypeName is different. That is the remote value is deserialized in comparison to the local output.
Results: After completing this exercise, you will have run commands against multiple remote computers.
MCT USE ONLY. STUDENT USE PROHIBITED
L09-71
$dc
2. To find a module on LON-DC1 that can work with Server Message Blocks (SMB) shares, run:
3. To import the module from LON-DC1 to your local computer, and to add the prefix DC to the
important commands’ nouns, run:
Get-DCSMBShare
Because this command implicitly runs on LON-DC1, the command will display shares for that
computer.
Get-SMBShare
Because you added the DC prefix to the imported commands, the local ones are still available by their
original name.
Get-PSSession | Remove-PSSession
2. Run:
Get-PSSession
MCT USE ONLY. STUDENT USE PROHIBITED
L09-72 Automating Administration with Windows PowerShell
Results: After completing this exercise, you will have used implicit remoting to import and run commands
from a remote computer.
MCT USE ONLY. STUDENT USE PROHIBITED
L09-73
2. To create remoting sessions to LON-CL1 and LON-DC1, and to save those in a variable, run:
$computers
Task 2: Create a report that displays Windows Firewall rules from two computers
1. To find a module capable of working with network security, run:
Notice the Get-NetFirewallRule command. To review the Help for the command, run:
Task 3: Create and display an HTML report that displays local disk information from
two computers. Your report must include each computer’s name, each drive’s letter, and
each drive’s free space and total size in bytes.
1. To display a list of local hard drives, filtered to include only those with a drive type of 3, run:
2. To run the same command on LON-DC1 and LON-CL1 by means of remoting, run:
3. To produce an HTML report containing the results of the previous command, run:
Get-PSSession |
Remove-PSSession
Results: After completing this exercise, you will have performed several management tasks against
multiple computers.
MCT USE ONLY. STUDENT USE PROHIBITED
L09-75
help *group*
help *user*
Results: After completing this exercise, you will have discovered the commands needed to perform the
remaining tasks in this lab.
MCT USE ONLY. STUDENT USE PROHIBITED
L09-76 Automating Administration with Windows PowerShell
2. To create a new user account that has the specified attributes, run:
Note: We must use single quotes here to wrap the password, as double quotes will imply replacing of
the variables, defined by $ sign, so for the above password containing $ symbols we must use single
quotes.
Enable-ADAccount HelpDeskTest
Results: After completing this exercise, you will have created a user group that represents the Help Desk
personnel, and added a new user account to that group for testing.
MCT USE ONLY. STUDENT USE PROHIBITED
L09-77
3. To create a custom session configuration file that has the specified attributes, run:
Although displayed here on multiple lines, this command must be typed as a single command line.
If you are receiving syntax or command errors, to try address the issue you could open notepad by
typing Notepad in the console and pressing return. Then in Notepad open
E:\Mod09\Labfiles\LONDC1-SessionConfig.ps1. You can then highlight the command and copy it,
then paste it into the console window to run it.
Results: After completing this exercise, you will have created a custom session configuration file.
MCT USE ONLY. STUDENT USE PROHIBITED
L09-78 Automating Administration with Windows PowerShell
As per Exercise 3, If you are receiving syntax or command errors to try address the issue you could
open notepad by typeing Notepad in the console and pressing return. Then in Notepad open
E:\Mod09\Labfiles\LONDC1-RegisterSession.ps1. You can then highlight the command and copy
it, then paste it into the console window to run it.
2. When you are prompted, enter the Administrator password Pa$$w0rd and click OK.
7. Make sure that the HelpDesk group has Full Control permissions selected.
8. Click OK.
9. Run:
Logoff
Results: After completing this exercise, you will have registered your custom session configuration.
MCT USE ONLY. STUDENT USE PROHIBITED
L09-79
Logoff
5. Press Enter.
It will take a minute to create the user profile after you log on.
6. On the Windows 8 Start screen, type power, and then click Windows PowerShell.
Note: We can use double quotes for the password here as it does not contain the $ symbol.
Get-Process
Get-Help Set-ADAccountPassword
You should receive an error as you do not have explicit permissions to the help file. Now also try the
option
Help Set-ADAccountPassword
11. Run:
Exit-PSSession
12. Run:
Logoff
2. In the Virtual Machines list, right click 10961A-LON-DC1, and then click Revert.
Results: After completing this exercise, you will have tested your custom session configuration.
MCT USE ONLY. STUDENT USE PROHIBITED
L10-81
2. Open File Explorer and create a folder named c:\scripts. You will use this folder during the lab.
Set-ExecutionPolicy RemoteSigned
6. In the Script pane, add the attribute and parameter block as shown in
E:\Mod10\LabFiles\Exercise_01_A.ps1:
[CmdletBinding()]
Param(
)
Task 2: Add input parameters to the script. Perform this task in the Script Pane
1. Create the parameters as shown in E:\Mod10\LabFiles\Exercise_01_B.ps1. Your script should contain
the following:
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True)]
[string]$MACAddress,
$LocalCredential = (Get-Credential -Message "Provide credential for target
machine"),
$DomainCredential = (Get-Credential -Message "Provide domain credential to add
machine to domain"),
[Parameter(Mandatory=$True)]
[string]$NewComputerName,
[Parameter(Mandatory=$True)]
[string]$NewIPAddress,
[Parameter(Mandatory=$True)]
[string]$Role,
[string]$Domain = "ADATUM",
[Parameter(Mandatory=$True)]
[string]$ScopeID,
[Parameter(Mandatory=$True)]
[string]$DHCPServerName
)
MCT USE ONLY. STUDENT USE PROHIBITED
L10-82 Automating Administration with Windows PowerShell
2. Press Ctrl+S.
Results: After completing this exercise, you will have created the beginnings of a parameterized script.
MCT USE ONLY. STUDENT USE PROHIBITED
L10-83
Exercise 2: Get the Dynamic IP Address of the New Server Core Computer
Task 1: Discover the MAC address of the LON-SVR1 computer
Note: In a real environment, you would have access to the MAC address either on a label (for a
physical computer) or through hypervisor configuration tools (for a virtual machine). In this task, you
will discover the information manually.
1. On the 10961A-LON-SVR1 virtual machine, log on by using the user name Administrator and the
password Pa$$w0rd.
2. Run:
ipconfig /all
Notice the 12-character physical address that is displayed as ‘‘00-1A-2B-3C-4D-5E’’. Your MAC
Address will be different. You will need this physical (MAC) address information throughout this lab.
Ensure that you write it down clearly, in an easy-to-access location.
$MACAddress = "01-23-45-01-23-45"
Replace ‘‘01-23-45-01-23-45’’ with the MAC address of the Server Core instance LON-SVR1.
You can confirm that the variable was defined as you expected by typing $MACAddress and
pressing enter. The value that the variable contains will display and you can verify it. This could be
done to double check all the variables that you will define as you proceed through this lab.
Note: You will not log on to LON-SVR1 again.
Task 2: In the Console pane, look up the IP address of the Server Core instance in the
DHCP server
1. Ensure you are still logged on to the 10961A-LON-CL1 virtual machine as Adatum\Administrator
with password Pa$$w0rd.
2. In the Windows PowerShell ISE, display the Console pane by clicking toolbar buttons or the blue
Hide/Show arrow icon. Or, press Ctrl+D.
Help *lease*
Notice the command Get-DhcpServerv4Lease. Read the command Help, and notice that it requires
you to specify a DHCP scope.
help *scope*
$DHCPServerName = "LON-DC1"
$ScopeID = "10.0.0.0"
$OldIPAddress = "$OldIPAddress"
$NewComputerName = "LON-SVR2"
Note: The existing name of the target computer is LON-SVR1. We will rename it to the name defined
in the variable $NewComputername as part of this process i.e. LON-SVR2.
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True)]
[string]$MACAddress,
$LocalCredential = (Get-Credential -Message "Provide credential for target
machine"),
$DomainCredential = (Get-Credential -Message "Provide domain credential to add
machine to domain"),
[Parameter(Mandatory=$True)]
[string]$NewComputerName,
[Parameter(Mandatory=$True)]
[string]$NewIPAddress,
[Parameter(Mandatory=$True)]
[string]$Role,
[string]$Domain = "ADATUM",
[Parameter(Mandatory=$True)]
[string]$ScopeID,
[Parameter(Mandatory=$True)]
[string]$DHCPServerName
)
$OldIPAddress = Get-DhcpServerv4Lease -ScopeId $ScopeID -ComputerName $DHCPServerName
|
Where-Object { $PSItem.ClientId -eq $MACAddress } |
Select-Object -ExpandProperty IPAddress |
Select-Object -ExpandProperty IPAddressToString
$OldIPAddress = "$OldIPAddress"
MCT USE ONLY. STUDENT USE PROHIBITED
L10-85
2. Press Ctrl+S.
Results: After completing this exercise, you will have written a command to retrieve an IP address from
the DHCP server based on the MAC address of the computer.
MCT USE ONLY. STUDENT USE PROHIBITED
L10-86 Automating Administration with Windows PowerShell
help *reservation*
$NewIPAddress = “10.0.0.10”
4. Run:
Note: You can verify the reservation has been created by going to Server Manager, then selecting
Tools and then DHCP.
The DHCP management console opens, and you should then right click DHCP and go to Add
Server... to add LON-DC1. Once LON-DC1 is added look at the values under lon-dc1\IPv4\Scope
[10.0.0.0] 10.0.0.0/24 Reservations ensuring 10.0.0.10 is listed.
Task 2: In the Script Pane, update your script to create the DHCP reservation
1. Modify your script as shown in E:\Mod10\Labfiles\Exercise_03_A.ps1. Your script should contain the
following:
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True)]
[string]$MACAddress,
$LocalCredential = (Get-Credential -Message "Provide credential for target
machine"),
$DomainCredential = (Get-Credential -Message "Provide domain credential to add
machine to domain"),
[Parameter(Mandatory=$True)]
[string]$NewComputerName,
[Parameter(Mandatory=$True)]
[string]$NewIPAddress,
[Parameter(Mandatory=$True)]
[string]$Role,
[string]$Domain = "ADATUM",
[Parameter(Mandatory=$True)]
[string]$ScopeID,
[Parameter(Mandatory=$True)]
[string]$DHCPServerName
)
$OldIPAddress = Get-DhcpServerv4Lease -ScopeId $ScopeID -ComputerName $DHCPServerName
|
Where-Object { $PSItem.ClientId -eq $MACAddress } |
Select-Object -ExpandProperty IPAddress |
Select-Object -ExpandProperty IPAddressToString
$OldIPAddress = "$OldIPAddress"
# Add a reservation
Add-DhcpServerv4Reservation -ClientId $MACAddress `
-IPAddress $NewIPAddress -ScopeId $ScopeID `
MCT USE ONLY. STUDENT USE PROHIBITED
L10-87
-ComputerName $DHCPServerName
2. Press Ctrl+S.
Results: After completing this exercise, you will have created a DHCP reservation for the LON-SVR1
computer.
MCT USE ONLY. STUDENT USE PROHIBITED
L10-88 Automating Administration with Windows PowerShell
$OriginalTrustedHosts
This may display a blank value if that is what was originally in your TrustedHosts list. Run Dir
WsMan:\localhost\Client and note the value that is listed for the Name TrustedHosts. Verify that
the value listed matches the TrustedHosts value that you just assigned to the $OriginalTrustedHosts
variable i.e. both may be blank.
Task 2: In the Console pane, add the Server Core computer's IP address to the
TrustedHosts list
1. To set the TrustedHosts list, run:
Dir WSMan:\localhost\Client
Verify that the TrustedHosts item is now set to the same value contained in $OldIPAddress.
Note the inverted commas around the $OriginalTrustedHosts variable in the command above. This is
to ensure the value is designated a string and read as such.
To verify the list, run:
Dir WSMan:\localhost\Client
Dir WSMan:\localhost\Client
MCT USE ONLY. STUDENT USE PROHIBITED
L10-89
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True)]
[string]$MACAddress,
$LocalCredential = (Get-Credential -Message "Provide credential for target
machine"),
$DomainCredential = (Get-Credential -Message "Provide domain credential to add
machine to domain"),
[Parameter(Mandatory=$True)]
[string]$NewComputerName,
[Parameter(Mandatory=$True)]
[string]$NewIPAddress,
[Parameter(Mandatory=$True)]
[string]$Role,
[string]$Domain = "ADATUM",
[Parameter(Mandatory=$True)]
[string]$ScopeID,
[Parameter(Mandatory=$True)]
[string]$DHCPServerName
)
$OldIPAddress = Get-DhcpServerv4Lease -ScopeId $ScopeID -ComputerName $DHCPServerName
|
Where-Object { $PSItem.ClientId -eq $MACAddress } |
Select-Object -ExpandProperty IPAddress |
Select-Object -ExpandProperty IPAddressToString
$OldIPAddress = "$OldIPAddress"
# Add a reservation
Add-DhcpServerv4Reservation -ClientId $MACAddress `
-IPAddress $NewIPAddress -ScopeId $ScopeID `
-ComputerName $DHCPServerName
# Save TrustedHosts
$OriginalTrustedHosts = Get-Item WSMan:\localhost\Client\TrustedHosts | select -
ExpandProperty value
# Set TrustedHosts
Set-Item WSMan:\localhost\Client\TrustedHosts -Value $OldIPAddress
# Restore TrustedHosts
Set-Item WSMan:\localhost\Client\TrustedHosts -Value “$OriginalTrustedHosts”
2. Press Ctrl+S.
Results: After completing this exercise, you will have saved your TrustedHosts list, and added the Server
Core computer’s IP address to it.
MCT USE ONLY. STUDENT USE PROHIBITED
L10-90 Automating Administration with Windows PowerShell
help *feature*
Notice the Add-WindowsFeature or Install-WindowsFeature commands (they are the same; the
first is an alias to the second).
$LocalCredential = Get-Credential
When prompted, provide the user name Administrator and the password Pa$$w0rd.
4. To add the Telnet Client role to the Server Core instance, run:
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True)]
[string]$MACAddress,
$LocalCredential = (Get-Credential -Message "Provide credential for target
machine"),
$DomainCredential = (Get-Credential -Message "Provide domain credential to add
machine to domain"),
[Parameter(Mandatory=$True)]
[string]$NewComputerName,
[Parameter(Mandatory=$True)]
[string]$NewIPAddress,
[Parameter(Mandatory=$True)]
[string]$Role,
[string]$Domain = "ADATUM",
[Parameter(Mandatory=$True)]
[string]$ScopeID,
[Parameter(Mandatory=$True)]
[string]$DHCPServerName
)
$OldIPAddress = Get-DhcpServerv4Lease -ScopeId $ScopeID -ComputerName $DHCPServerName
|
Where-Object { $PSItem.ClientId -eq $MACAddress } |
Select-Object -ExpandProperty IPAddress |
Select-Object -ExpandProperty IPAddressToString
$OldIPAddress = "$OldIPAddress"
# Add a reservation
Add-DhcpServerv4Reservation -ClientId $MACAddress `
-IPAddress $NewIPAddress -ScopeId $ScopeID `
-ComputerName $DHCPServerName
# Save TrustedHosts
$OriginalTrustedHosts = Get-Item WSMan:\localhost\Client\TrustedHosts |
select -ExpandProperty value
# Set TrustedHosts
MCT USE ONLY. STUDENT USE PROHIBITED
L10-91
2. Press Ctrl+S.
Results: After completing this exercise, you will have added a role to the Server Core computer.
MCT USE ONLY. STUDENT USE PROHIBITED
L10-92 Automating Administration with Windows PowerShell
help *computer*
Notice the Add-Computer command. Write down four parameters that are needed to add a
computer to a domain, to rename the computer while adding it, and to restart the computer.
$DomainCredential = Get-Credential
When prompted, provide the user name ADATUM\Administrator and the password Pa$$w0rd.
Task 2: In the Script Pane, update your script to add and rename the computer
1. Modify your script as shown in E:\Mod10\Labfiles\Exercise_06_A.ps1. Your script should contain the
following:
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True)]
[string]$MACAddress,
$LocalCredential = (Get-Credential -Message "Provide credential for target
machine"),
$DomainCredential = (Get-Credential -Message "Provide domain credential to add
machine to domain"),
[Parameter(Mandatory=$True)]
[string]$NewComputerName,
[Parameter(Mandatory=$True)]
[string]$NewIPAddress,
[Parameter(Mandatory=$True)]
[string]$Role,
[string]$Domain = "ADATUM",
[Parameter(Mandatory=$True)]
[string]$ScopeID,
[Parameter(Mandatory=$True)]
[string]$DHCPServerName
)
$OldIPAddress = Get-DhcpServerv4Lease -ScopeId $ScopeID -ComputerName $DHCPServerName
|
Where-Object { $PSItem.ClientId -eq $MACAddress } |
Select-Object -ExpandProperty IPAddress |
Select-Object -ExpandProperty IPAddressToString
$OldIPAddress = "$OldIPAddress"
# Add a reservation
Add-DhcpServerv4Reservation -ClientId $MACAddress `
-IPAddress $NewIPAddress -ScopeId $ScopeID `
-ComputerName $DHCPServerName
# Save TrustedHosts
$OriginalTrustedHosts = Get-Item WSMan:\localhost\Client\TrustedHosts |
select -ExpandProperty value
MCT USE ONLY. STUDENT USE PROHIBITED
L10-93
# Set TrustedHosts
Set-Item WSMan:\localhost\Client\TrustedHosts -Value $OldIPAddress
# Install role
Invoke-Command –ComputerName $OldIPAddress `
–Credential $LocalCredential `
–ScriptBlock { Install-WindowsFeature Telnet-Client }
# Add to domain and rename
Invoke-Command –ComputerName $OldIPAddress `
–Credential $LocalCredential `
–ScriptBlock { param($x,$y) Add-Computer –DomainName ADATUM `
–NewName $x `
–Credential $y `
–Restart } `
–ArgumentList $NewComputerName,$DomainCredential
# Restore TrustedHosts
Set-Item WSMan:\localhost\Client\TrustedHosts -Value “$OriginalTrustedHosts”
2. Press Ctrl+S.
Results: After completing this exercise, you will have renamed the Server Core computer and added it to
the domain.
MCT USE ONLY. STUDENT USE PROHIBITED
L10-94 Automating Administration with Windows PowerShell
In the preceding command, provide the MAC address of the Server Core instance in place of 00-15-
5D-24-3D-14. You should have written down the MAC address in an earlier exercise.
In the preceding command, provide the DHCP scope IP address in place of 10.0.0.0. You should have
written down the scope IP address in an earlier exercise.
When you are prompted for the local credential, provide the user name Administrator and password
Pa$$w0rd.
When you are prompted for the domain credential, provide user name ADATUM\Administrator and
password Pa$$w0rd.
Wait for the script to complete, and then wait a few minutes for the Server Core instance to restart.
Note: It is expected that the target computer will restart and you will loose your connection. The
LON-CL1 is attempting to connect to the old IP Address and will not successfully reconnect as the IP
Address has een changed ot the new address. In the console prompt you will see an error message
saying ‘‘..Connection Lost..’’ attempting to reconnect. You will then receive a WinRM Security
Configuration prompt, and press Y to confirm after which the script will stop running.
To verify that the computer is in the domain, on LON-CL1 in with Windows PowerShell console run:
Get-ADComputer –filter *
Dir WSMan:\localhost\Client
2. In the Virtual Machines list, right click 10961A-LON-DC1, and then click Revert.
Results: After completing this exercise, you will have automated the provisioning process and verified the
results.
MCT USE ONLY. STUDENT USE PROHIBITED
L10-96
MCT USE ONLY. STUDENT USE PROHIBITED
L11-97
2. Press the Windows logo key, type Windows PowerShell, right click the Windows PowerShell tile, and
click Run as administrator.
3. To enable remoting on LON-CL1, run the following command and answer Yes by typing Y at each
prompt:
Enable-PSRemoting
4. To start a remoting job that retrieves a list of physical network adapters from LON-DC1 and LON-CL1,
run:
5. To start a remoting job that retrieves a list of Server Message Block (SMB) shares from LON-DC1 and
LON-CL1, run:
6. To start a remoting job that retrieves all instances of the Win32_Volume class from every computer
in Active Directory® Domain Services, run:
Because not every computer in the domain may be online, this job may not complete successfully.
That is expected.
This job is expected to take a very long time to complete. Do not wait for it to complete proceed to
the next task.
Results: After completing this exercise, you will have started jobs using two of the basic job types.
MCT USE ONLY. STUDENT USE PROHIBITED
L11-98 Automating Administration with Windows PowerShell
Get-Job
3. To display a list of running jobs whose names start with remote, run:
Results: After completing this exercise, you will have managed the jobs that you created in the previous
exercise.
MCT USE ONLY. STUDENT USE PROHIBITED
L11-99
4. Run:
Logoff
6. Log on to LON-CL1 using user name ADATUM\Administrator and the password Pa$$w0rd.
2. Type powershe.
3. Right-click the Windows PowerShell icon and click Run as Administrator.
MCT USE ONLY. STUDENT USE PROHIBITED
L11-100 Automating Administration with Windows PowerShell
Import-Module PSScheduledJob
Get-Job
2. In the Virtual Machines list, right-click 10961A-LON-DC1, and then click Revert.
3. In the Revert Virtual Machine dialog box, click Revert.
Results: After completing this exercise, you will have created and run a scheduled job, and retrieved the
results from the job.
MCT USE ONLY. STUDENT USE PROHIBITED
L12-101
3. Run the following command and answer Yes to the prompt by typing Y.
Set-ExecutionPolicy RemoteSigned
4. Run the file E:\Mod12\Labfiles\Lab12.ps1 by typing the below and pressing Enter.
. E:\Mod12\Labfiles\Lab12.ps1
Notice that there are a period and a space before the E:\
$ComputerNames[1]
8. Produce a comma-separated string that contains the values in the array $ComputerNames.
10. In the variable $Phrase, replace the word dog with the word gelding.
11. $List contains a comma-separated list. Display the second value in this list.
$phrase.ToUpper()
MCT USE ONLY. STUDENT USE PROHIBITED
L12-102 Automating Administration with Windows PowerShell
$phrase.ToLower()
4. In $phrase, replace the value over with the value around, and display an all-uppercase version of the
result.
$phrase.Replace('over','around').ToUpper()
$List.Substring(5,3)
6. Display the contents of $padded so that there are no additional spaces before or after value.
$padded.Trim()
$phrase.Length
8. Display True or False, depending on whether the contents of $phrase starts with the value The.
$phrase.StartsWith('The')
9. Display the contents of $unpadded so that 10 additional spaces are added before value.
$unpadded.PadLeft(10)
$today = Get-Date
$today.AddDays(-10)
$today.AddDays(30)
$today.Hour
$today.Month
$today.ToShortDateString()
$today.ToUniversalTime()
MCT USE ONLY. STUDENT USE PROHIBITED
L12-103
$today.ToLongTimeString()
Results: After completing this exercise, you will have practice with using several Windows PowerShell
techniques.
MCT USE ONLY. STUDENT USE PROHIBITED
L12-104 Automating Administration with Windows PowerShell
2. Switch to the LON-DC1 virtual machine and type cd\ at the command prompt
3. Then type dir and press Enter.
4. IN the list if files returned verify there is a file present called C:\users.csv
Results: After completing this exercise, you will have practiced how to use alternative credentials.
MCT USE ONLY. STUDENT USE PROHIBITED
L12-105
Cd c:\
$cred = Get-Credential –Credential ADATUM\Administrator
4. Press Ctrl+S.
5. In the tree view on the left, expand Libraries and then expand Documents.
6. Select Documents
7. If the WindowsPowerShell folder does not exist, click New folder. Type WindowsPowerShell for
the folder name, and press Enter.
8. Double-click the WindowsPowerShell folder.
9. In the File name text box, type Profile.ps1 and press Enter.
$PSDefaultParameterValues=@{"Get-EventLog:LogName"="Security";"Get-
EventLog:Newest"=10}
3. Press Ctrl+S.
(If the Windows PowerShell icon doesn’t exist in the taskbar you can open the Start Screen and type
Power, then right clicking the resultant Windows PowerShell icon and selecting the Pin to taskbar
option.)
5. Run Get-EventLog. Verify that 10 entries from the Security log are shown.
2. In the Virtual Machines list, right click 10961A-LON-DC1, and then click Revert.
Results: After completing this exercise, you will have created a profile script.
MCT USE ONLY. STUDENT USE PROHIBITED
Notes
MCT USE ONLY. STUDENT USE PROHIBITED
Notes
MCT USE ONLY. STUDENT USE PROHIBITED
Notes
MCT USE ONLY. STUDENT USE PROHIBITED
Notes
MCT USE ONLY. STUDENT USE PROHIBITED
Notes
MCT USE ONLY. STUDENT USE PROHIBITED
Notes
MCT USE ONLY. STUDENT USE PROHIBITED
Notes
MCT USE ONLY. STUDENT USE PROHIBITED
Notes
MCT USE ONLY. STUDENT USE PROHIBITED
Notes
MCT USE ONLY. STUDENT USE PROHIBITED
Notes
MCT USE ONLY. STUDENT USE PROHIBITED
Notes
MCT USE ONLY. STUDENT USE PROHIBITED
Notes
MCT USE ONLY. STUDENT USE PROHIBITED
Notes
MCT USE ONLY. STUDENT USE PROHIBITED
Notes