PowerShell for the IT Administrator Part 1 Lab Manual v1.1

December 22, 2016 | Author: birroz | Category: N/A
Share Embed Donate


Short Description

Curso PowerShell...

Description

PowerShell for the IT Administrator, Part 1 Student Lab Manual (v1.1)

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Conditions and Terms of Use Microsoft Confidential - For Internal Use Only

This training package is proprietary and confidential, and is intended only for uses described in the training materials. Content and software is provided to you under a Non-Disclosure Agreement and cannot be distributed. Copying or disclosing all or any portion of the content and/or software included in such packages is strictly prohibited. The contents of this package are for informational and training purposes only and are provided "as is" without warranty of any kind, whether express or implied, including but not limited to the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. Training package content, including URLs and other Internet Web site references, is subject to change without notice. Because Microsoft must respond to changing market conditions, the content should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information presented after the date of publication. Unless otherwise noted, the 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.

© 2012 Microsoft Corporation. All rights reserved.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Copyright and Trademarks © 2012 Microsoft Corporation. All rights reserved.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in 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. 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. For more information, see Use of Microsoft Copyrighted Content at http://www.microsoft.com/about/legal/permissions/ Microsoft®, Internet Explorer®, and Windows® are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. Other Microsoft products mentioned herein may be either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. All other trademarks are property of their respective owners.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 4 of 361

Contents LESSON 1 DEMONSTRATION : INTRODUCTION ............................................................................................... 9 HOW TO USE THE EXAMPLES IN THIS WORKSHOP ............................................................................................ 10 EXERCISE 1: WINDOWS POWERSHELL ......................................................................................................... 14 EXERCISE 2: THE POWERSHELL INTEGRATED SCRIPTING ENVIRONMENT (ISE) ........................................................ 17 EXERCISE 3: POWERSHELL V2.0 INSTALLATION AND PREREQUISITES .................................................................... 20 EXERCISE 4: BASIC POWERSHELL COMMANDS ............................................................................................... 23 EXERCISE 5: RUNNING EXTERNAL COMMANDS ............................................................................................... 26 EXERCISE 6: LIST POWERSHELL COMMANDS .................................................................................................. 28 EXERCISE 7: GETTING HELP WITH POWERSHELL.............................................................................................. 30 EXERCISE 8: EXPLORE COMMAND HISTORY ................................................................................................... 32 LESSON 1 HANDS-ON : INTRODUCTION ........................................................................................................ 34 EXERCISE 1: CREATE A TRANSCRIPT OF COMMANDS ........................................................................................ 35 EXERCISE 2: USING THE MOST COMMON COMMANDS..................................................................................... 37 EXERCISE 3: RUN MULTIPLE COMMANDS ..................................................................................................... 39 LESSON 2 DEMONSTRATION : COMMANDS AND OBJECTS............................................................................ 41 EXERCISE 1: POWERSHELL COMMANDS ........................................................................................................ 42 EXERCISE 2: COMMAND ALIASES ................................................................................................................ 47 EXERCISE 3: THE OBJECT-BASED SHELL ......................................................................................................... 49 EXERCISE 4: THE .NET OBJECT MODEL ........................................................................................................ 56 LESSON 2 HANDS-ON : COMMANDS AND OBJECTS....................................................................................... 60 EXERCISE 1: POWERSHELL COMMANDS ........................................................................................................ 61 EXERCISE 2: DISCOVERING OBJECT MEMBERS ................................................................................................ 65 EXERCISE 3: CREATING OBJECT INSTANCES .................................................................................................... 68 LESSON 3 DEMONSTRATION : PIPELINE ........................................................................................................ 72 EXERCISE 1: UNDERSTAND THE FUNDAMENTAL OPERATORS .............................................................................. 73 EXERCISE 2: UNDERSTAND PIPELINE USAGE, SYNTAX, AND THE PIPELINE VARIABLE ................................................... 78 EXERCISE 3: FILTERING , SORTING, AND GROUPING DATA .................................................................................. 82 EXERCISE 4: PIPELINE INPUT AND OUTPUT .................................................................................................... 87 LESSON 3 HANDS-ON : PIPELINE ................................................................................................................... 91 EXERCISE 1: POWERSHELL OPERATORS ........................................................................................................ 92 EXERCISE 2: THE POWERSHELL PIPELINE ....................................................................................................... 94 EXERCISE 3: FILTER AND SORT WITH THE PIPELINE ........................................................................................... 98 LESSON 4 DEMONSTRATION : PROVIDERS .................................................................................................. 103 EXERCISE 1: PROVIDER I NTRODUCTION........................................................................................................104 EXERCISE 2: PROVIDER RELATED CMDLETS AND OPERATIONS............................................................................108

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 5 of 361

EXERCISE 3: SINGLE LEVEL PROVIDERS ........................................................................................................115 EXERCISE 4: MULTIPLE LEVEL PROVIDERS .....................................................................................................120 LESSON 4 HANDS-ON : PROVIDERS ............................................................................................................. 129 EXERCISE 1: WORK WITH ENVIRONMENT PROVIDER .......................................................................................130 EXERCISE 2: WORK WITH THE CERTIFICATE PROVIDER .....................................................................................133 EXERCISE 3: WORKING WITH THE REGISTRY PROVIDER ....................................................................................136 LESSON 5 DEMONSTRATION : VARIABLES AND TYPE FUNDAMENTALS ....................................................... 139 EXERCISE 1: WORKING WITH VARIABLES ......................................................................................................140 EXERCISE 2: BASIC VARIABLE TYPES IN POWERSHELL ......................................................................................145 EXERCISE 3: WORKING WITH ARRAYS .........................................................................................................153 EXERCISE 4: WORKING WITH HASH TABLES ..................................................................................................157 EXERCISE 5: WORKING WITH CONSOLE INPUT-OUTPUT ...................................................................................160 EXERCISE 6: WORKING WITH FILES .............................................................................................................162 EXERCISE 7: POWERSHELL ERROR OBJECT ....................................................................................................166 LESSON 5 HANDS-ON : VARIABLES AND TYPE FUNDAMENTALS .................................................................. 171 EXERCISE 1: WORKING WITH VARIABLES ......................................................................................................172 EXERCISE 2: WORKING WITH ARRAYS .........................................................................................................174 EXERCISE 3: WORK WITH HASH TABLES .......................................................................................................176 EXERCISE 4: WORK WITH HASH TABLES AND CALCULATED OBJECT PROPERTIES .....................................................178 LESSON 6 DEMONSTRATION : SCRIPTING ................................................................................................... 181 EXERCISE 1: SCRIPTING IN POWERSHELL ......................................................................................................183 EXERCISE 2: ITERATION STATEMENTS ..........................................................................................................189 EXERCISE 3: FLOW CONTROL STATEMENTS ...................................................................................................193 EXERCISE 4: OTHER STATEMENTS ..............................................................................................................196 EXERCISE 5: FUNCTIONS ..........................................................................................................................200 EXERCISE 6: PROFILES .............................................................................................................................206 EXERCISE 7: DOT SOURCING AND SCRIPT LIBRARIES ........................................................................................209 LESSON 6 HANDS-ON : SCRIPTING .............................................................................................................. 211 EXERCISE 1: CREATE POWERSHELL SCRIPTS ..................................................................................................212 EXERCISE 2: CREATE FUNCTIONS IN SCRIPTS .................................................................................................213 EXERCISE 3: CREATE POWERSHELL PROFILES ................................................................................................214 EXERCISE 4: EXPLORE ITERATION STATEMENTS IN POWERSHELL ........................................................................215 LESSON 7 DEMONSTRATION : ACTIVE DIRECTORY ADMINISTRATION (ADSI) .............................................. 219 EXERCISE 1: ACTIVE DIRECTORY FUNDAMENTALS ...........................................................................................220 EXERCISE 2: SEARCHING ACTIVE DIRECTORY .................................................................................................224 EXERCISE 3: THE DIRECTORY OBJECT LIFECYCLE .............................................................................................230 LESSON 7 HANDS-ON : ACTIVE DIRECTORY ADMINISTRATION (ADSI) ......................................................... 239

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 6 of 361

EXERCISE 1: CREATE MULTIPLE USERS ........................................................................................................240 LESSON 8 DEMONSTRATION : ACTIVE DIRECTORY ADMINISTRATION (CMDLETS)....................................... 244 EXERCISE 1: USING THE ACTIVE DIRECTORY MODULE .....................................................................................245 EXERCISE 2: USING THE ACTIVE DIRECTORY PROVIDER ....................................................................................247 EXERCISE 3: CMDLETS AND IDENTITY...........................................................................................................249 EXERCISE 4: SEARCHING ACTIVE DIRECTORY USING CMDLETS ............................................................................252 EXERCISE 5: CREATING ACTIVE DIRECTORY OBJECTS USING CMDLETS ..................................................................254 EXERCISE 6: MODIFYING OBJECTS USING CMDLETS ........................................................................................256 EXERCISE 7: POWERSHELL CREDENTIAL OBJECTS AND USING ALTERNATIVE CREDENTIALS FOR CMDLETS ......................257 LESSON 8 HANDS-ON : ACTIVE DIRECTORY ADMINISTRATION (CMDLETS).................................................. 258 EXERCISE 1: CREATING MULTIPLE USERS IN AN ORGANIZATIONAL UNIT ..............................................................259 EXERCISE 2: MODIFYING AD OBJECTS VIA CMDLETS .......................................................................................262 EXERCISE 3: SEARCHING AD OBJECTS VIA CMDLETS ........................................................................................264 LESSON 9 DEMONSTRATION : WINDOWS MANAGEMENT INSTRUMENTATION (WMI)............................... 267 EXERCISE 1: INTRODUCTION TO WMI .........................................................................................................268 EXERCISE 2: WMI CLASSES AND QUERIES ....................................................................................................272 EXERCISE 3: WMI REMOTING AND METHOD EXECUTION ................................................................................281 EXERCISE 4: COMMON WMI CLASSES USED ................................................................................................286 LESSON 9 HANDS-ON : WINDOWS MANAGEMENT INSTRUMENTATION (WMI).......................................... 290 EXERCISE 1: WMI CLASSES AND QUERIES ....................................................................................................291 EXERCISE 2: BASIC FILTERING ....................................................................................................................293 EXERCISE 3: WMI METHOD EXECUTION .....................................................................................................296 LESSON 10 DEMONSTRATION : REGISTRY, EVENT LOG AND ACL MANAGEMENT ........................................ 301 EXERCISE 1: USING THE REGISTRY PROVIDER ................................................................................................302 EXERCISE 2: REMOTE REGISTRY MANAGEMENT .............................................................................................310 EXERCISE 3: EVENTLOG CMDLETS...............................................................................................................315 EXERCISE 4: FILE AND FOLDER ACL MANAGEMENT ........................................................................................320 LESSON 10 HANDS-ON : REGISTRY, EVENT LOG AND ACL MANAGEMENT................................................... 322 EXERCISE 1: READING REGISTRY INFORMATION FROM A REMOTE HOST ...............................................................323 EXERCISE 2: SEARCHING EVENT LOGS FOR EVENTS .........................................................................................326 EXERCISE 3: FILE AND FOLDER ACL MANAGEMENT ........................................................................................330 LESSON 11 DEMONSTRATION : REMOTING................................................................................................. 334 EXERCISE 1: REMOTE MANAGEMENT WITHOUT POWERSHELL REMOTING ............................................................335 EXERCISE 2: ENABLE POWERSHELL REMOTING ..............................................................................................338 EXERCISE 3: ENABLE POWERSHELL REMOTING WITH THE ACTIVE DIRECTORY GROUP POLICY OBJECT (GPO)................340 EXERCISE 4: EXECUTE A SINGLE REMOTE COMMAND OR SCRIPT ........................................................................342 EXERCISE 5: CREATE A PERSISTENT SESSION TO EXECUTE A SERIES OF REMOTE COMMANDS .....................................345

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 7 of 361

EXERCISE 6: CREATE AN INTERACTIVE SESSION WITH A REMOTE MACHINE ...........................................................348 EXERCISE 7: CREATE A SESSION CONFIGURATION ...........................................................................................350 LESSON 11 HANDS-ON : REMOTING............................................................................................................ 354 EXERCISE 1: EXECUTE REMOTE COMMANDS .................................................................................................355 EXERCISE 2: EXECUTE COMMANDS VIA SESSIONS ...........................................................................................357 EXERCISE 3: INTERACTIVE REMOTE CONSOLE ................................................................................................359

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 8 of 361

PowerShell for the IT Administrator, Part 1 Lesson 1: PowerShell Introduction

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 9 of 361

Lesson 1 Demonstration : Introduction Introduction The way this lesson is presented is a little different to what you might be used to. You would have noticed that there is no workbook and that we are starting with the lab manual. What we are going to do is walk through some examples as an instructor led lab format and then you will complete some lab exercises by yourself.

Objectives After completing this lab, you will be able to: 

Understand the basic use and capabilities of Windows PowerShell



Meet the pre-requisites and install Windows PowerShell



Run basic PowerShell commands



Use PowerShell help to get help about PowerShell commands

Prerequisites To complete this lab, you need: 

A Windows 7 workstation logged onto with administrator credentials. You can logon as contoso\administrator. The password is P@ssword

Estimated Time to Complete this Lab 60 minutes

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 10 of 361

How to use the Examples in this Workshop The way with lesson will be presented will be a little different to what you may be used to. You would have noticed that there is no workbook and that we are starting with the lab manual. What we are going to do is walk through the examples together as an instructor led lab format, and then you will do some more lab exercises by yourself. There are three options you can choose from for following the examples: 

Manually type in the commands



Open the command files in the PowerShell Integrated Scripting Environment (ISE) and execute each command by selecting each one



Using the automated start-demo PowerShell script to run each command automatically

Each option is a matter of preference. The first option will familiarize you with the commands. This is the slowest option and you may have problems keeping up with the instructor, but this is a great option to run through after the workshop at your own pace to consolidate your learning. The second and third options are easier as they do not require type each command. However, as you are not typing each command you may miss some commands. If you use the second option, the command file can be opened and commands can still be typed using the command pane. This allows you to run some of the command from the file and type others. The third option is the easiest option to run the demo commands. However, you cannot enter additional commands manually. This can be easily solved by opening a second PowerShell console and typing the additional commands.

Option 1: Run Commands Manually This option is to type the command in manually as they appear in the code blocks of each example. You can use tab completion in PowerShell to reduce typing time. Also You can use the up arrow to select the most recent commands executed if you need to build from the previous command.

Option 2: Use of Command Files and the ISE To use the ISE and the command files, change the default view of the ISE to maximize the Real Estate screen. To maximize the Real Estate screen, 1. Select the Start button to open the PowerShell ISE. 2. Type ISE and run the Windows PowerShell ISE. By default, it will appear as follows:

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 11 of 361

Figure 1

3. Click one of the three rightmost buttons in the toolbar to adjust the pane arrangement. This makes it easier to follow all examples.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 12 of 361

Figure 2

In this view, 1. Open the command file, or files for the lesson. 2. Select each line that does not start with #. 3. Press F8 or right-click and select Run or click the

icon on the toolbar.

Option 3: Use of Start-Demo Script Using the start-demo script is the easiest option. To use this option, your PowerShell console should be opened as normal and the location should be changed to C:\Pshell\part1\lesson1 for lesson 1. 1. To change the location, type: set-location c:\pshell\part1\lesson1

2. Now type the following command to load the start-demo.ps1 script function into the memory: . .\start-demo.ps1

The dot and space before .\start-demo are required.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 13 of 361

3. Now type the following command to start the demo script: Start-demo

Where is the demo script file for the lesson or exercise. Note: To exit the demo script at any time you can use the ctrl + c keys.

The script will display the last line number used. 4. To restart the script type the following command: Start-demo

Where line number is the number of the line to re-start from.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 14 of 361

Exercise 1: Windows PowerShell Objectives In this exercise, you will: 

Learn what Windows PowerShell is



Open Windows PowerShell and run some basic commands

Scenario Welcome to Windows PowerShell. Windows PowerShell is both a command shell and a scripting language. A significant difference between PowerShell and other shells is that it is an object-oriented shell. This aspect of PowerShell will be discussed in detail later. The use of Windows PowerShell can be divided into two main areas: 

Running commands from the command shell interactively



Running scripts

Running scripts will be discussed later. For now, we will discuss running commands in the shell. Both categories of use of PowerShell are powerful. Depending on the task being performed will determine which category to use. For example, Exchange 2007 or 2010 administrators will be familiar with running commands in the command shell but they may not be familiar with running scripts. We will start with opening PowerShell and running commands in the console.

Task 1: Log on to the VM Environment 1. Log on to the Windows 7 client. 2. Open Windows PowerShell and run the required commands.

Task 2: Open Windows PowerShell for the First Time There are different methods to open Windows PowerShell. Each method has its own purpose. The first one we use is the simplest. 1. Open PowerShell. 2. On the Windows taskbar, click

(PowerShell icon).

The PowerShell window appears. You will notice that it looks different to the standard command prompt. It should have a blue background and white text. It will also have the text PS C:\users\administrator> PS indicates that you are using PowerShell and not the CMD shell.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 15 of 361

Task 3: Run the First Command 1. Type the following command: dir

You will see that now you have displayed the files and folders that are available from your current location. Let us compare the PowerShell display and the CMD shell display. 2. Click Start > Run, type cmd and press Enter. 3. In the CMD shell, type the following command: dir

4. Compare the output of PowerShell and the output of the CMD shell. You will notice that they are very different. The main advantage of PowerShell is that it is easy to change the view.

Task 4: Change PowerShell View 1. In the PowerShell console, type the following command to display the file system objects: dir | format-table name, lastwritetime, length

You will see that we now have the same information but it appears very differently. Now let us open PowerShell from the run box. It will look different. 2. Click Start > Run, type powershell and press Enter. The PowerShell prompt appears, but this time you will see it looking more like the CMD shell, as it has the black backgorund and the grey text. Note that it will have the PS C:\users\administator> prompt. 3. In the PowerShell console, type the following command to display the file system objects: dir | format-table name, lastwritetime, length

You will notice that the output is the same as in the blue background window. Now, close the black background window and let us run another command in the blue background window. 4. Type the following command to display processes. get-process

A list of all the processes running on your machine appears. Now, run the same command from the command prompt. 5.

Click Start > Run and type the following command: powershell –command get-process

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 16 of 361

You will see the command run and produce the output, but the window closes as soon as it finishes running the command. To prevent this, you have the option of keeping the window open after you run the command. You will do this now using the noexit option. Note that this needs to be before the –command option. 6. Click Start > Run and type the following command: PowerShell –noexit –command get-process

You will now see that the command is executed and the window stays open. You can explore other options for running PowerShell.exe and commands by typing PowerShell /?

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 17 of 361

Exercise 2: The PowerShell Integrated Scripting Environment (ISE) PowerShell v2.0 comes with its own graphical scripting editor known as the ISE. The ISE is a fully integrated scripting environment that both aids in using PowerShell and enhances it. The ISE is installed by default on Windows 7 machines, and installed automatically on workstations as part of the Windows management framework package (that includes PowerShell v2). On Windows Server 2008 R2, it is a feature that you have to enable, or select to install on other operating systems. Once you have the ISE available then it can be run. 1. On your workstation click Start > Run and type PowerShell ISE and press Enter. The PowerShell ISE opens and you will see the three parts of it.

Figure 3

Script Pane Allows you to create and run scripts. You can open, edit, and run existing scripts in the Script Pane.

Output Pane Displays the results of the commands and scripts you have run. You can also copy and clear the contents in the Output Pane.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 18 of 361

Command Pane Allows you to type commands. You can run a one-line command or a multi-line command in the Command Pane. Press SHIFT+ENTER to enter each line of a multiline command, and press Enter after the last line to execute the mult-line command. The prompt displayed on top of the Command Pane shows the path to the current working directory. From here, we can run PowerShell commands and view the results.

Task 1: Run PowerShell 1. Click the Command pane and type the following command: dir | format-table name, lastwritetime, length

You will now see in the output pane the results of the command. This is just like having a PowerShell console open, but we are running these commands from within the ISE. Now will we run some commands from the script pane. 2.

Click the Script pane and type the following: get-process

You can open the file _ISE-commands.ps1 if you do not want to type the commands. 3. On the next line, type the following command: dir | format-table name, lastwritetime, length

4. On the next line type the following: write-host “Hello from PowerShell!”

You will notice that the ISE will now color code the different parts of each command. This is to help identify the different parts of each command such as the command part, and strings code blocks.

Task 2: Run All Commands You can now run all commands using the Run button(or press F5) or select the line or part of the line to be run. 1. Drag and select the text you want to run. 2. Use the Run selection button or press F8 to run the command. 3. Select the first line that has get-process and select the text. 4. Select the Run selection button or press F8 to run the command. You will see that in the output pane, you have the results of the get-process command. 5. Select the second line with dir | format-table name, lastwritetime, length and run this selection. The output for this command appears in the output pane.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 19 of 361

6. Click the Run button or press F5 to run all the commands. You will see the output of all commands. 7. Keep the ISE open and run commands in it, or close the ISE and run commands in the PowerShell.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 20 of 361

Exercise 3: PowerShell V2.0 Installation and prerequisites Before you run PowerShell, you must make sure it is available. PowerShell v2.0 is installed by default on Windows 7 and Windows Server 2008 R2. Therefore, for these operating systems you do not have to do anything additional to make PowerShell available. For operating systems other than Windows 7 and Windows Server 2008 R2 , you will need to download and install the Windows Management Framework package. It is available from http://support.microsoft.com/default.aspx/kb/968929. This package will install Windows PowerShell 2.0, WinRM 2.0, and BITS 4.0. The update can be installed on the following operating systems: 

Windows Server 2008 with Service Pack 1



Windows Server 2008 with Service Pack 2



Windows Server 2003 with Service Pack 2



Windows Vista with Service Pack 2



Windows Vista with Service Pack 1



Windows XP with Service Pack 3



Windows Embedded POSReady 2009



Windows Embedded for Point of Service 1.1

In addition to the Windows Management Framework package, the .NET framework 3.5 SP1 is also required on the system to install PowerShell v2.0. Although PowerShell v1 is available, there are many new features of PowerShell v2.0 that should be considered. PowerShell v1 is available for the following systems: 

Windows Server 2003 with Service Pack 2



Windows XP with Service Pack 3

PowerShell v1.0 is installed by default, on Windows Vista and as a feature for Windows Server 2008. The requirements for PowerShell v1.0, are that the .NET framework 2.0 is installed on the system. At this stage, it is not recommended that PowerShell v1 be installed, as v2 has many additional features available. By default, all versions of PowerShell will have the execution of scripts disabled. This has to be turned on either by the command set-execution policy or via group policy/registry settings. For PowerShell v2, PowerShell Remoting is also disabled by default. This has to be enabled with the command enable-psremoting or via group policy/registry settings.

Task 1: Determine the PowerShell Version There are several ways you can determine the version of PowerShell you are currently running, or is available on a machine. We will look at several of these and a few things of note.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 21 of 361

Use of $host.version 1. In the PowerShell console, type the following command to display the version: $host.version

This will now display the version number of Windows PowerShell. The number to take the most note of is the major version number.

Use of $psversiontable 1. In the PowerShell console, type the following command to view the ps version table: $psversiontable

This table of version numbers not only gives you the version of PowerShell installed but also lists the version of other related components. This is useful when you start looking at some of the advanced features of PowerShell such as remoting. The number to take interested in here is the PSVersion number.

Use of Registry You can also check the version of PowerShell installed on a machine by checking the registry. This can be very useful, as it will allow us to check the version of PowerShell installed on a remote machine without having to run commands in a PowerShell console. 1. In the PowerShell console, type the following command to get the version information from the registry: get-itemproperty HKLM:\software\microsoft\PowerShell\1\PowerShellEngine

You will now see the information from the registry key. The properties to take note of are the runtimeversion and the powershellversion number. You can use the same path on a remote machine to check the PowerShell version installed on the target. This will be discussed later.

Use of PSSnapins By looking at the versions of the PowerShell snapins you can determine the version of PowerShell and see the versions of each snapin that makes up the collections of PowerShell Cmdlets. 1. In the PowerShell console, type the following command to list the PowerShell snap-ins: get-pssnapin

You will now see the current PowerShell snapins and their PowerShell version numbers.

Points to Note About PowerShell v2.0 There are a few things to take note of when looking at PowerShell and its version. Several things such are registry paths, file extensions and install locations did not change between PowerShell v1 and PowerShell v2. These can cause confusion about the version of PowerShell that is in use. First to note is that the file extension .PS1 is still the script file extension for PowerShell v2.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 22 of 361

The next is the PowerShell install location. 1. In the PowerShell console, type the following to set the location to the PowerShell install location: $pshome

This variable contains the path to the PowerShell install location. Note that even on a machine with PowerShell v2 installed, this still points to %systemroot%\ System32\WindowsPowerShell\v1.0. The registry path for PowerShell v2 is also HKLM:\software\microsoft\PowerShell\1\.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 23 of 361

Exercise 4: Basic PowerShell Commands In this exercise, you will run some basic PowerShell commands. PowerShell allows you to run both PowerShell commands, many of these called Cmdlets, and external commands such as executable. First, you need to create a transcript to record all the commands you type. This will log all commands and the output they produce. 1. In the PowerShell console, type following command to start a transcript start-transcript PowerShell_transcript.txt

This will now start the transcript recording our commands. You will get a quick list of the commands available to run in PowerShell. To do this, use the Cmdlet called get-command. Transcript commands will not work if you are running the demos from within the ISE

2. In the PowerShell console, type the following command to list the commands available. get-command

A list of commands available to you under the current PowerShell console appears. However, you will notice that this list contains different types of commands. For now, you need only Cmdlets. Use get-command to display only the Cmdlets. 3. In the PowerShell console, type the following command to list Cmdlets: get-command –commandtype cmdlet

This will now list just the Cmdlets. You will notice it is a much shorter list than before. In fact you can use PowerShell to tell exactly how many Cmdlets there are. You can do this easily using two different methods. 4. In the PowerShell console, type the following command to count the Cmdlets available: get-command –commandtype cmdlet | measure-object

The count of available Cmdlets appears. By default, in Windows 7 the count should be 236 at the time of writing. There is another way to do this. 5. In the PowerShell console, type the following command to count the Cmdlets available: (get-command –commandtype cmdlet).count

The number of Cmdlets appears. However, this time you will see only the number. Now let us run some more commands. 1. In the PowerShell console, type the following command to get the current date: get-date

The current date and time appears. You can change what appears by using some parameters in the command.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 24 of 361

2. In the PowerShell console, type the following command to get just the date: get-date –displayhint date

Only the date appears. 3. In the PowerShell console, type the following command to get only the current time: get-date –displayhint time

Only the time appears. You can also view different time formats. 1. In the PowerShell console, type the following to display the short date format: get-date –displayhint time –format d

2. In the PowerShell console, type the following command to display the long date format: get-date –displayhint time –format D

3. In the PowerShell console, type the following to display the short time format: get-date –displayhint time –format t

4. In the PowerShell console, type the following command to display the long time format: get-date –displayhint time –format T

5. In the PowerShell console, type the following to display the date in a given format: get-date –displayhint time –format yyyy/MM/dd

This will display the date in the given format. Note that this is case sensitive. Note also that you should always use ISO8601 for dates rather than a specific locale. 6. In the PowerShell console, type the following command to display time in a given format: get-date –displayhint time –format hh:mm:ss

This will display the time in the given format. Again, note that this is case sensitive and the lower-case ‘mm’ produces minutes, whereas the upper-case ‘MM’ produces the month. Let us look at something more interesting. 1. In the PowerShell console, type the following command to list the current processes: get-process

A list of the currently running processes appears. We can do the same with services. 2. In the PowerShell console, type the following command to list the services on the system: get-service

A list of services and their statuses appears. However, you might be interested in only one service. You can view this by typing its name after get-service. Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 25 of 361

3. In the PowerShell console, type the following command to get information for just the bits service: get-service bits

Now you will see information about only the bits service 4. In the PowerShell console, type the following command to generate a random number between 1 and 10: Get-random –Minimum 1 –Maximum 10

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 26 of 361

Exercise 5: Running External Commands The great thing about PowerShell is that you do not have to call the external command with anything special to get them to run. You can run the command by typing the name of the command and pressing Enter. 1. In the PowerShell console, type the following command to get IP configuration information: ipconfig

You will now see that you have the same output that you would have had if you run the command in the CMD shell. 2. In the PowerShell console, type the following command to get all IP configuration information: ipconfig /all

You will again see the same output as the CMDshell. 3. In the PowerShell console, type the following command to get system information: systeminfo

This will now list a summary of the system information of the current machine. What may be useful is to write this information to a file. Just like the CMD shell, you can use the > and >> symbols to redirect the output. > will overwrite the output, whereas >> will append the output. 4. In the PowerShell console, type the following command to redirect output to a file: systeminfo >systeminfo.txt

This will now write that information to a text file for us. To view it lets use notepad 5. In the PowerShell console, type the following command to open the text file in notepad: notepad systeminfo.txt

You will now see the information from the command in the text file. This not only works for external commands, but also for Cmdlets. 6. In the PowerShell console, type the following command to redirect the Cmdlet output to a file: get-service > services.txt

7. In the PowerShell console, type the following command to read the file: notepad services.txt

The information about services appears. You can also get PowerShell to run multiple commands in a sequence. This can be useful as you can put multiple commands in one line and PowerShell will run these in a sequence. This

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 27 of 361

is especially useful if you have a command that takes a while to run and you do not want to wait until it is finished. To do this, use the semicolon character. This is the statement terminator for PowerShell. 1. In the PowerShell console, type the following command to run multiple commands, add multiple items to a text file and open it in Notepad: ipconfig /all > systemconfig.txt; systeminfo >>systemconfig.txt ; get-service >>systemconfig.txt; notepad systemconfig.txt

The three commands to get information about the system will now run, and each of these will put information into the systemconfig.txt. Finally, open Notepad to view this information. The $lastexitcode variable can be very useful when working with external commands. This variable contains the exit code or errorlevel value from the external command. In general, an exit code of zero is a success and anything non-zero is considered an error of some type. However, this may not be true depending on the program you are running. Let us look at a simple example using the ping command. 1. In the PowerShell console, type the following command to ping the local machine: ping localhost

2. In the PowerShell console, type the following command to check the status of the previous command: $lastexitcode

You will now see that the value of the $lastexitcode is now zero. This is because we were able to ping the localhost. 3. In the PowerShell console, type the following command to ping a non-existing host: ping fakeserver

4. In the PowerShell console, type the following command to check the status of the previous command: $lastexitcode

You will now see that the value of the $lastexitcode is now one. This is because, you were unable to ping the fakeserver host, as it does not exist.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 28 of 361

Exercise 6: List PowerShell Commands You looked at listing available PowerShell commands quickly a little while ago. But it is worth spending a little more time on this as it is difficult to remember around 236 or more commands. There will be a number of Cmdlets that you will use repeatedly, and some you may never use. To help you find Cmdlets in PowerShell we have the get-command Cmdlet. This can be used in a number of ways to find the commands that you are interested in. 1. In the PowerShell console, type the following command to list the commands available: get-command

You will now see a list of Cmdlets, functions and alias. This does work a little differently in PowerShell v1 and v2. In v1 you would have only seen Cmdlets by default. 2. In the PowerShell console, type the following command to list just Cmdlets: get-command –commandtype cmdlet

You will now see a list of just the Cmdlets available. Now, let us look for commands that start with get. 3. In the PowerShell console, type the following command to list all the command that start with get: get-command

get*

A list of commands that start with get appears. You will notice that most of these are Cmdlets. However, there are some external commands such as getmac.exe and gettingstarted.exe listed. This is because, these are commands that PowerShell can run. You will notice that these external commands are listed as the type of application. This tells you that it is an external command. If you combine the last two options, commandtype and get* you will see only the Cmdlets. 4. In the PowerShell console, type the following command to list just Cmdlets that start with get: get-command –commandtype cmdlet get*

Now, you will see just Cmdlets that start with get. There is an easier way to do this. You can use the -verb option to look for Cmdlets or functions. 5. In the PowerShell console, type the following command to list Cmdlets with the verb get: get-command –verb get

You will now see any Cmdlets and functions that have the verb get in their name. We will go into more details about the naming of Cmdlets later, but you will find that the names of the Cmdlets follow verb-noun in their names. This makes it easy to know what a Cmdlet might do, but also makes is easy to find the Cmdlets.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 29 of 361

6. In the PowerShell console, type the following command to list Cmdlets with the noun service: get-command –noun service

7. You will now see all the Cmdlets that are related to services. We can also do this with a wildcard search. 8. In the PowerShell console, type the following command to get all commands that end with service: get-command *service

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 30 of 361

Exercise 7: Getting Help with PowerShell One of the useful things with PowerShell is that it has a great built-in help system. All Cmdlets have a help topic and these topics have both, a consistent format and a consistent method for accessing it. This is all done with the Cmdlet get-help. In addition, to having help information for Cmdlets, there are also additional help topics covering PowerShell concepts, 1. In the PowerShell console, type the following command to display the help details: get-help

The help information for the get-help Cmdlet appears. You will notice that information follows a particular format. The good thing is that this format is the same for all Cmdlets. 2. In the PowerShell console, type the following command to get help on the get-command Cmdlet: get-help get-command

The help information for the get-command Cmdlet appears. You can expand on this by using two options. 3. In the PowerShell console, type the following command to get a detailed help on getcommand: get-help get-command –detailed

Some of the same information as before appears on top of the display. However, as you scroll down you will find more information such as the parameter descriptions and some examples. Let us do this again with a different Cmdlet. 4. In the PowerShell console, type the following to get detailed help on get-service Cmdlet: get-help get-service –detailed

The detailed help information for the get-service Cmdlet appears. There is another option that is useful, the –full option. This will display all the help information for the Cmdlet. 5. In the PowerShell console, type the following to get all help on get-service Cmdlet: get-help get-service –full

The full help information for that Cmdlet appears. Another option that can be a great way to jog your memory about how a Cmdlet works is the –examples option. This will display some examples of how to use the Cmdlet. 6. In the PowerShell console, type the following command to get just examples of the getservice Cmdlet: get-help get-service –examples

In addition to getting help on Cmdlets, there are many other help topics available. To see them we will use the following command.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 31 of 361

7. In the PowerShell console, type the following command to list all help topics: get-help *

The full list of help topics available appears. You will see the alias, the functions, Cmdlets and finally the helpfile topics. You will notice that all the helpfile topics all have the name about_ this allows us to look just at them. 8. In the PowerShell console, type the following command to list just the about topics: get-help about

Only the information about helpfile topics appears. 9. In the PowerShell console, type the following command to display the wildcards help topic: get-help about_wildcards

The information about PowerShell wildcards appears. Note that there is no –full or – detailed option with the about topics.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 32 of 361

Exercise 8: Explore Command History One of the things that can help a lot in the early stages of learning PowerShell is to look at the history of the commands that you have run. This can be done in a few different methods, but we will look at the two main methods. The first is using the get-history Cmdlet to display the previous commands run. 1. In the PowerShell console, type the following command to view the command history: get-history

The previous commands run up to a default maximum of 64 commands. You will notice that each command has an ID associated with it. This ID can be used to re-run a particular command. 2. In the list of commands, locate the ID for the get-help and get-service commands. 3. In the PowerShell console, type the following command to invoke the command from history: invoke-history –id

The command executes again. This can be useful when you have complicated lines of code and you do not want to use the up arrow to go through all commands again. The previous commands can also be exported and later imported to use again. 1. In the PowerShell console, type the following command to export the history to a csv file: get-history | export-csv myhistory.csv

The command history is exported to a CSV file. 2. Open a new PowerShell console and type the following command to view the current history: get-history

As this is a new PowerShell session, you will see that there currently are no commands in the history. You can now import the commands from the CSV file we created to include some history commands that can be invoked. 3. In the new PowerShell console, type the following command to import the history from the other session: import-csv myhistory.csv | add-history

4. In the new PowerShell console, type the following command to view the current history: get-history

You will now see that there are commands loaded into the history and can be invoked. Notice that the IDs will not be the same as the session that we exported the information from.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 33 of 361

One thing to note is that by default, you will only see the last 64 commands. This number is defined by the variable $MaximumHistoryCount. To increase the maximum commands: 1. In the original PowerShell console, type the following command to increase the maximum command history count: $MaximumHistoryCount = 100

This will allow you to look at up to 100 previous commands. You can also specify – count 100 for get history to display the 100 commands. By default, you will only get 32 displayed. 2. In the PowerShell console, type the following command to get the last 100 commands: get-history –count 100

There is another way of viewing the previous commands run. However, this will also show the output produced from each of these. If you remember, earlier in the lesson, we created a transcript. This will have recorded all the previous commands that we have run. So let us stop and view the contents of that transcript. 1. In the PowerShell console, type the following command to stop the transcript: Stop-Transcript

This will stop recording of the session and tell you where the output file is. Again, remember here (and moving forward through the additional demonstrations) that transcript commands will fail if being run through the ISE.

2. In the PowerShell console, type the following to read the transcript: notepad

By reading the file, you will see the history of all the commands you have run. This file should be kept for later use, as it can be useful to look at the commands you have run. It is suggested that at least for the next few lessons, start a transcript for each lesson so that you can review those later. In addition to the history Cmdlets, you can also use the up arrow to see the previous commands run. To run the same command again, press Enter. You can also use the up arrow to bring up a previous command and modify it. The drawback here is that if you need to go back several commands, or you need to re-run multiple commands, the order of these commands will change each time a new command is executed.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 34 of 361

Lesson 1 Hands-On : Introduction Objectives The objectives for this lab are: 

To create transcripts of PowerShell commands



To practice using the top 3 Cmdlets (i.e. get-help, get-command and get-member)



To execute multiple commands in a single line

Prerequisites 

The lab requires a Windows 7 client running in a domain environment.

Estimated time to complete this lab 30 minutes

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 35 of 361

Exercise 1: Create a Transcript of Commands Objectives In this exercise, you will: 

Practice creating transcripts of PowerShell commands

Task 1: Log on to the VM environment 1. Log on to Windows 7 Enterprise client as Contoso\Administrator with the password, P@ssword

Task 2: Open Windows PowerShell Session On the Windows taskbar, click

.

The PowerShell window appears.

Task 3: Record commands in a text file 1. Type the following in the PowerShell console. This will NOT work in the PowerShell ISE as transcripts are not supported under the ISE Host. new-item -path $home\documents -name transcripts -type directory

This will create a new directory for storing transcript files. 2. Type the following to set the transcript variable to a desired location for storing transcript files $global:transcript=”$home\documents\transcripts\$((getdate).tostring("yyyyMMddHHmmss")).txt”

Note: This global variable will be lost when the PowerShell session is terminated. The variable assignment can be added to a Profile if it is required to persist between sessions. Note also that you should always use ISO8601 for dates rather than a specific locale as shown in tostring("yyyyMMddHHmmss")) above.

3. Type the following to start the recording part of this PowerShell session in a text file. start-transcript.

4. Enter some commands, for example: Get-command Get-service Get-process Get-help

5. Type the following to stop recording this PowerShell session.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 36 of 361

stop-transcript

Note that the file path and name appears on the console. 6. Type the following to view the transcript file name. notepad $transcript

7. Type the following to start recording again. start-transcript

8. Enter some commands, for example: Get-command -commandtype Cmdlet

9. Type the following to stop recording this PowerShell session. stop-transcript

Note that the file path and name appears on the console. 10. Type the following to view the transcript file name. notepad $transcript

Note that the same file is used and the previous content was overwritten. 11. Type the following to start recording again start-transcript -append

12. Enter some commands, for example: Get-command -commandtype alias

13. Type the following to stop recording this PowerShell session. stop-transcript

Note that the file path and name appears on the console. 14. Type the following to view the transcript file name. notepad $transcript

Note that the same file is used and the previous content is still available.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 37 of 361

Exercise 2: Using the Most Common Commands Objectives In this exercise, you will: 

Practice using the most common and useful PowerShell commands

Task 1: Log on to the VM environment 1. Log on to Windows 7 Enterprise client as Contoso\Administrator with the password, P@ssword

Task 2: Open Windows PowerShell Session On the Windows taskbar, click

.

The PowerShell window opens.

Task 3: Get-Help, Get-Command and Get-Member 1. Type the following to view the full help available on using the get-help Cmdlet. 2.

get-help get-help -full

Type the following to view help for the get-command Cmdlet.

get-help get-command

3. Type the following to view help for the get-member Cmdlet. get-help get-member

4. Type the following to return the methods and properties that are available for the output of the (get-help get-command) command. (get-help get-command) | get-member

5. Type the following to return only the properties that are available for the output of the (get-help get-command) command. (get-help get-command) | get-member -membertype noteproperty

6. Type the following to return only the methods that are available for the output of the (gethelp get-command) command. (get-help get-command) | get-member -membertype method

7. Type the following to display the command syntax only. (get-help get-command).syntax

8. Type the following to display all the parameters of the command. (get-help get-command).parameters

9. Type the following to view the static members of the datetime type. [datetime] | get-member -static

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 38 of 361

A. Type the following to view the current date and time. [datetime]::now

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 39 of 361

Exercise 3: Run Multiple Commands Objectives In this exercise, you will: 

Explore running multiple PowerShell commands in a single line

Task 1: Log on to the VM environment 1. Log on to Windows 7 Enterprise client as Contoso\Administrator with the password, P@ssword

Task 2: Open Windows PowerShell Session On the Windows taskbar, click

.

The PowerShell window opens.

Task 3: Multiple Commands 1. Type the following series of commands on a single line write-output. The text is wrapped here due to the page width. Write-Output “Asset Information`n” | out-file $home\documents\assetinfo.txt; get-date | out-file $home\documents\assetinfo.txt -append; $Env:COMPUTERNAME | out-file $home\documents\assetinfo.txt -append; get-service | out-file $home\documents\assetinfo.txt –append

2. Type the following command to view the asset information. notepad "$home\documents\assetinfo.txt"

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 40 of 361

PowerShell for the IT Administrator, Part 1 Lesson 2: PowerShell Commands Student Lab Manual

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 41 of 361

Lesson 2 Demonstration : Commands and objects Introduction This lab introduces PowerShell commands, known as cmdlets. You will learn about cmdlet usage, discovery and syntax for a complete understanding of their importance. You will also understand the concept of objects, which is fundamental to using PowerShell effectively.

Objectives After completing this lab, you will be able to: 

Explore command discovery, syntax and usage



Leverage command help topics



Discover & create command aliases



Explain the usage of classes, objects & various object models in PowerShell

Pre-requisites To complete this lab, you need: 

A Windows 7 workstation logged onto with administrator credentials

Estimated time to complete this lab 60 minutes

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 42 of 361

Exercise 1: PowerShell Commands Objectives In this exercise, you will: 

Learn command syntax



Learn command usage



Find command help



Discover commands and their grouping

Scenario PowerShell consists of four types of commands: 

Cmdlets



Functions



Scripts



External commands

In this exercise, we will focus on using the first type of commands, known as Cmdlets (pronounced ‘command-lets’). Cmdlets are commands ‘built-in’ to PowerShell. They are written in a .NET language (C#, VB.NET, F#, etc.) and compiled into a dynamic link library (.DLL) file. 236 Cmdlets are available by default in PowerShell v2.0 and cover a wide range of uses, from interacting with the file system to listing event log and service information. Although out-of-scope for this lesson, it is worth noting that new Cmdlets authored and compiled by a developer can be loaded into the PowerShell process, alongside the default Cmdlets.

Task 1: Understand the Command Syntax Commands have a verb-noun naming convention, where the verb describes the action to take on the noun. Nouns are always named in a singular way (Process rather than Processes). It is also worth noting that PowerShell is not case sensitive. Command names are followed by a number of hyphen-prefixed parameter names which may be paired with an argument and are known as named parameters. All parameters and their arguments are separated by one or more space characters. Parameter arguments can also be inferred by their position in the command without specifying the parameter name. These are known as positional arguments.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 43 of 361

Name

Verb-Noun

Switch Parameter

Parameter with argument

–parameter1

–parameter2

Positional argument



1. Open the PowerShell console or ISE and type the following command: Get-Process

This command will return a list of all processes running on the local machine. 2. To limit the number of processes returned, add a parameter and an argument. The following example uses the Get-Process Cmdlet’s –Name parameter. Get-Process -Name explorer

This will return a single line of information about the “explorer” process running on the local machine. 3. Parameter names can also be shortened by abbreviating them to a unique value. Get-Process -Na explorer

4. Next, try typing the same command using PowerShell’s tab-completion feature. Type the following: Get-

Then, press the Tab key until the full command name appears. Pressing SHIFT+TAB moves backwards through the list. 5. This feature also works with parameter names. Type a space character and a hyphen character. Pressing the Tab key will cycle through all the parameters for a particular command. Again, pressing Shift+Tab moves backwards through the list. Get-Process -

6. Certain parameter names can be omitted entirely with the command still working as expected. Below, the argument explorer is associated with the –Name parameter by its position in the command. Remember that the arguments have to be passed in the default order specified by the Cmdlet. Get-Process explorer

7. Many parameters also accept a list of arguments, allowing more than one value to be bound to a parameter. In PowerShell, lists can be specified by separating each item with a comma. Get-Process –Name explorer,system,wmiprvse

8. Now add a parameter that does not require an argument. Such parameters are called switch parameters, since they change the command's behavior by enabling a feature within it.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 44 of 361

For example, the module switch parameter of the Get-Process Cmdlet turns on a feature that lists all the .dll files loaded by the returned process. Get-Process -Name explorer -Module

9. If you omit any required parameters, PowerShell will prompt you to supply the required arguments automatically. In the example below, you are prompted for the -Path and Type parameter arguments to successfully create a new folder on the local C: volume. PS C:\Users\Administrator> New-Item cmdlet New-Item at command pipeline position 1 Supply values for the following parameters: Path[0]: c:\test Path[1]: Type: directory Directory: C:\ Mode ---d----

LastWriteTime ------------11/08/2011 10:00 PM

Length Name ------ ---test

Task 2: Search for Commands (Get-Command) In this task, you will understand how to search for Cmdlets. To do this, use a Cmdlet designed specifically for this purpose. The Get-Command Cmdlet returns a list of commands. 1. Open the PowerShell console or ISE. 2. Type the following command and press Enter: Get-Command

A list of Cmdlets, Functions and Aliases will be displayed, since all command types are listed by default. 3. If you were searching for a command containing a particular string you can enclose it in wildcard (*) characters. Get-Command *item*

4. Get-Command also has –verb and –noun parameters which allow you to limit the search to commands matching the verb and/or noun part of the name. Below we list all the Cmdlets where the word on the left-hand side of the hyphen, the verb, matches the string “get”. Get-Command –verb get

Wildcard characters can also be used in parameter arguments. 5. List all the commands where the noun part of the name starts with the string ‘object’. Get-Command –noun object

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 45 of 361

6. List all commands where the verb part of the name ends with the letter ‘w’. Get-Command –verb *w

Task 3: Get Command Help (Get-Help) PowerShell has an extensive help system accessible through the Get-Help Cmdlet. The Cmdlet can return the syntax, description, parameters and examples for any command. 1. To use this Cmdlet, type the name of the command you want help for as the first argument. Get-Help New-Item

This use of the command displays basic help information. Get-Help also has a number of switch parameters that control the amount of help information returned. The -full parameter returns all information about a particular command. Get-Help Get-Service -full

The -examples parameter lists different ways in which a command can be used. Get-Help New-Item -examples

The -detailed parameter adds examples and descriptions to the basic help. Get-Help New-Item -detailed

As with all commands, wildcard characters can be used to return help for multiple matches. If only one command matches, PowerShell returns the help for that command. If not, a list of matching help topics is displayed. Get-Help new*

Another useful switch parameter for this Cmdlet is -Online. If you have internet access, this parameter will open the TechNet Windows PowerShell command Help Topics documentation for the specified command. http://technet.microsoft.com/enus/library/dd347701.aspx. Get-Help New-Item -Online

2. Get-Help can also be used to display conceptual help about the PowerShell Language. This is accessed by using the argument about_*, which will list all of the conceptual help topics. Get-Help about_*

You can then choose the topic and use its full name to list the entire help file. Get-Help about_Command_Syntax

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 46 of 361

Note: A very useful piece of information returned by all the Get-Help switch parameters is the command syntax. This has a special format that is easy to understand, once you know how to interpret it!

Microsoft | Services

-]

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 47 of 361

Exercise 2: Command Aliases In the previous exercise, the full verb-noun name was used when calling commands. Using aliases, PowerShell provides the ability to create alternate names for any command. Note: Aliases execute the underlying command using a different name.

There are two types of built-in aliases: Transitional and Convenience. Transitional aliases: Transitional aliases were created to assist users migrating from cmd.exe or UNIX/Linux shells to PowerShell. For example, the cmd.exe dir command lists files and folders in the current directory. In UNIX/Linux shells, the same operation is achieved using the ls command. PowerShell implements two transitional aliases for its equivalent directory listing Cmdlet, Get-ChildItem. The following commands both execute Get-ChildItem. dir ls

Convenience aliases: Convenience aliases are, as the name suggests, for convenience. For example, Get-ChildItem has a convenience alias of gci, which saves the time required to type the complete command name. gci

Note: By default, PowerShell 2.0 has 137 aliases. The majority can be re-assigned to point to a different command or deleted entirely, although they will be re-populated when a new console or ISE session is established.

Task 1: Find Different Alias Commands 1. Find all the ‘*-Alias’ commands using either of the methods below: Get-Command –Name *alias Get-Command –Noun alias

You will see five Cmdlets that can be used to manipulate aliases. The most useful of which are Get-Alias, New-Alias and Set-Alias. a. The Get-Alias Cmdlet is used to list all aliases. Get-Alias

b. New-Alias allows you to create new aliases for a Cmdlet, Function or executable file. The -Name parameter argument specifies the name of the new alias and the -Value parameter specifies the command to alias. New-Alias –Name gp –Value Get-Process

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 48 of 361

c. The Set-Alias Cmdlet can point an existing alias to a different command. Set-Alias –Name gp –Value Get-PSProvider

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 49 of 361

Exercise 3: The Object-based Shell Traditionally, the Windows command console and UNIX shells process data in the form of strings. While this is a common way to represent data, it is not easy to extract and manipulate the data. Character sequences need to be found using regular expressions or line/column numbers and converted into the required string format for another command to process. In contrast, PowerShell is an object-based shell built on the .NET framework. Objects are a mechanism to store and manipulate data in a structured way. Data does not have to be extracted from strings and can be accessed using a simple naming convention. Note: PowerShell’s language is based on a POSIX standard shell (IEEE Spec. 1003.2), which itself is based on the UNIX Bourne Shell (Windows PowerShell in Action – Second Edition, Manning Press 2011 by Bruce Payette).

What is an Object? Objects are all around us. A car is an object with a collection of separate parts, such as a steering wheel, accelerator pedal and brakes. To drive the car, we can use the parts to steer, accelerate and slow/stop the vehicle. We can now divide the car (object) into two distinct concepts. 

A collection of parts



Uses of the parts to change the car’s behavior

Now, apply this object model to the Windows Operating System. A Windows Service object has a collection of parts called Properties. Properties represent the state of a service, such as the service name and status. The service status can be changed by using object Methods. Object Methods allow you to start or stop a service. Collectively, properties and methods are called object Members. Members

Properties

Methods

Service Name

Start()

Status

Stop()

Note: Method names can be easily distinguished from property names as they are always appended with a pair of smooth brackets ‘()’.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 50 of 361

Task 1: List Object Information (Get-Member Cmdlet) The .NET object framework is self-descriptive. All objects hold information that describes their structure. You can interrogate any .NET object and list its properties and methods within PowerShell without needing to refer to the online MSDN Class Library. You can achieve this by passing the object through the pipeline, to the Get-Member Cmdlet. Pipeline operations will be covered in detail in another lesson. 1. Get a list of process objects using the Get-Service Cmdlet and pipe them to the GetMember Cmdlet. This will list the members (properties & methods) of this type of object. Get-Service | Get-Member

2. Alternatively, you can choose not to use the pipeline and employ the Get-Member Cmdlet’s InputObject parameter. This command however lists the members of the collectin of pipeline data as a whole, rather than the individual items in the collection. Get-Member –InputObject (Get-Service)

The top of the output lists the type name of the object(s). In the first case when piping to Ger-Member, you can see it is a System.ServiceProcess.ServiceController type of object. TypeName: System.ServiceProcess.ServiceController

The next piece of information displayed is the collection of members (properties and methods). The output below displays three columns of member information: the name, membertype and definition. Name MemberType ------------Name AliasProperty RequiredServices AliasProperty Disposed Event Close Method Continue Method CreateObjRef Method Dispose Method Equals Method ExecuteCommand Method GetHashCode Method GetLifetimeService Method GetType Method InitializeLifetimeService Method Pause Method Refresh Method Start Method Stop Method ToString Method WaitForStatus Method CanPauseAndContinue Property CanShutdown Property CanStop Property Container Property

Microsoft | Services

Definition ---------Name = ServiceName RequiredServices = ServicesDependedOn System.EventHandler Disposed(System.Object, System.Void Close() System.Void Continue() System.Runtime.Remoting.ObjRef System.Void Dispose() bool Equals(System.Object obj) System.Void ExecuteCommand(int command) int GetHashCode() System.Object GetLifetimeService() type GetType() System.Object InitializeLifetimeService() System.Void Pause() System.Void Refresh() System.Void Start(), System.Void System.Void Stop() string ToString() System.Void System.Boolean CanPauseAndContinue {get;} System.Boolean CanShutdown {get;} System.Boolean CanStop {get;} System.ComponentModel.IContainer Container

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 51 of 361

DependentServices DisplayName MachineName ServiceHandle ServiceName ServicesDependedOn ServiceType Site Status

Property Property Property Property Property Property Property Property Property

System.ServiceProcess.ServiceController[] System.String DisplayName {get;set;} System.String MachineName {get;set;} System.Runtime.InteropServices.SafeHandle System.String ServiceName {get;set;} System.ServiceProcess.ServiceController[] System.ServiceProcess.ServiceType System.ComponentModel.ISite Site

3. The PowerShell code below returns the number of members that a System.ServiceProcess.ServiceController object contains. Note: Pipeline operations will be covered in more detail in the next lesson).

You can see that there are 32 members of a System.ServiceProcess.ServiceController object. Get-Service | Get-Member | Measure-Object -Property MemberType Count Average Sum Maximum Minimum Property

: 32 : : : : : MemberType

4. It is possible to shorten the output from this Cmdlet by listing only the properties. Get-Service | Get-Member –MemberType property

5. It is also possible to shorten the output by listing only the methods. Get-Service | Get-Member –MemberType method

6. Now that you have uncovered the object’s members, you can use them to access state information using properties and manipulate the object using methods.

Task 2: Access Object Members To access information stored in object properties or execute object methods, the dot (.) character is used to separate the object name from the member name. This is referred to as dot-notation. 1. Select a single service object by filtering the output of the Get-Service Cmdlet using the Name parameter and assign it to a variable. $ALGService = Get-Service –Name alg

2. Type the variable name to confirm that you have referenced the correct service. By default, three properties of the service object are displayed: Status, Name and DisplayName.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 52 of 361

$ALGService Status -----Running

Name ---ALG

DisplayName ----------Application Layer Gateway Service

3. Type a dot (.) character directly after the variable name and repeatedly press the Tab key. The member names for this object type will be displayed one after the other. 4. Press Enter to display the information stored in one of the properties. $ALGService.DisplayName Application Layer Gateway Service

5. Type the variable name again, followed by a dot, and type Start(). Press Enter. Note: Be sure to append smooth brackets ‘()’ after the method name. $ALGService.Start()

6. Type the variable name to view the service status. Note that the status is still stopped. This is because the state of the service was saved at the instant you assigned it to a variable in step 1. Following the assignment, the state has not been updated. 7. To update the status property, execute the object’s Refresh() method. $ALGService.Refresh()

8. The status property should now display Running. $ALGService Status -----Running

Name ---ALG

DisplayName ----------Application Layer Gateway Service

9. Let’s see another example of accessing object members. Assign a string to a variable and pass it through the pipeline to Get-Member to discover the string object’s members. Alternatively, you can use the alias for Get-Member (gm). $strMyName = “My name is Chris” $strMyName | Get-Member

10. You can also just pipe the string directly to the Get-Member Cmdlet. Both commands in steps 8 and 9 produce the same output. “My name is Chris” | Get-Member

11. The object type name returned is System.String. This type has 2 properties and 32 methods. The length property stores the number of characters in the string. In this case, the string consists of 16 characters. $strMyName.length 16

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 53 of 361

Alternatively, call the property using the string, rather than the variable. Again, both commands produce identical output. (“My name is Chris”).length 16

Note: Even though the parenthesis are not required above, it makes sense to have them since it applies to other types of commands where this is not possible without parenthesis.

Try calling a few of the object methods. o

The Split() method splits the string on every occurrence of a space character and returns an array. $strMyName.Split() My name is chris

o

The Substring() method returns a part of the string. This method requires input parameters to be provided within the parenthesis to represent the startIndex. $strMyName.Substring(11) Chris

o

The Replace() method replaces a substring of characters with another. This method requires two input parameters: 

The string to find



The string to replace it with

$strMyName.Replace("Chris","John") My name is John

Note: The $strMyName variable is never modified by any of the methods and still contains the original string.

Task 3: Use the *-Object Cmdlets PowerShell has a group of Cmdlets that can manipulate any type of object. This Cmdlet is typically used in a pipeline operation. Pipeline operations will be covered in detail in another lesson. 1. List the *-Object Cmdlets. Get-Command –noun Object CommandType Name ----------- ----

Microsoft | Services

Definition ----------

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 54 of 361

Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet

Compare-Object ForEach-Object Group-Object Measure-Object New-Object Select-Object Sort-Object Tee-Object Where-Object

Compare-Object [-ReferenceObject… ForEach-Object [-Process] Role Administration Tools> AD DS and AD LDS Tools. 4. Ensure that Active Directory Module for Windows PowerShell is checked. Similarly, on Windows Server 2008 R2, you can install the Active Directory module for PowerShell by using the Add Features Wizard. You can follow one of the steps mentioned below to load the Active Directory module for Windows PowerShell. 5. On the Start menu, click on Administrative Tools and then click on Active Directory Module for Windows PowerShell. The AD Web Service (ADWS) running on a Domain Controller is discovered and the Active Directory module is loaded. If the service does not exist or is stopped, the Active Directory module will fail to load. On the windows Task Bar, locate and click the icon. This will open the Windows PowerShell menu. 6. At the PS prompt type the following command. get-module -ListAvailable

The output lists of all the modules can be imported into the session. 7. Now type the following command. Import-Module Activedirectory

8. You can list all cmdlets available from this module, as follows: Get-Command -Module "ActiveDirectory"

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 247 of 361

Exercise 2: Using the Active Directory Provider Scenario In the previous modules, you have learned that Windows PowerShell Providers are .NET Framework based programs that make the data in a specialized data store available, to allow you to work as if they were mounted drives. Administrators can use the Active Directory module provider to navigate and access data stored in the Active Directory domains. The Active Directory module provider exposes the Active Directory database through a hierarchical navigation system, which is very similar to the file system. For example, while you are using the Active Directory module, you can use the following commands to navigate through your directory: Cd, dir, remove

Task Description 1. You can use the Active Directory module provider to map Active Directory domains to specific provider drives. When the Active Directory module is first loaded, a default Active Directory drive (AD:) is mounted with the root path set to RootDSE of the local forest. To connect to the AD: drive, run the following command: PS c:\>cd AD:\

2. To enumerate the partitions in the forest, use dir (gci/get-childitem) PS AD:\> Get-ChildItem Name ---contoso Configuration Schema

ObjectClass ----------domainDNS configuration dMD

DistinguishedName ----------------DC=contoso,DC=com CN=Configuration,DC=contoso,DC=com CN=Schema,CN=Configuration,DC=contoso,DC=com

The Active Directory provider can be used to easily connect to any of the partitions to query or make changes. 3. To connect to a domain, type the following command: PS AD:\> Cd “dc=contoso,dc=com” PS AD:\DC=contoso,DC=com>

4. Using dir, you can enumerate the objects in the domain, as follows: PS AD:\DC=contoso,DC=com> dir

5. You can also connect to a child OU or container using its Distinguished Name (DN) or Relative Distinguished Name (RDN). The following command will set the location to the drive AD:\OU=Test,DC=contoso,DC=com

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 248 of 361

PS AD:\DC=contoso,DC=com>cd “OU=test”

6. The Active Directory PSProvider can be used to create a PSDrive, which connects to the Active Directory with specific or logged on credentials. The following command creates a new provider drive to an Active Directory domain using the New-PSDrive cmdlet: New-PSDrive -PSProvider ActiveDirectory -Name Contoso ` -Root "AD:\dc=contoso,dc=com"

The other optional parameters commonly used with the cmdlet New-PSDrive are Server and Credential. 7. In order to use the domain, server, credentials or set the search base to a specific path of the drive, set the location (cd) to the created PSDrive. PS c:\>set-location PS Contoso:\>

Contoso:\

Certain generic cmdlets shown in the following table can be used with the Active Directory provider. Get-PSProvider

New-PSDrive

Get-PSDrive

Remove-PSDrive

Get-ChildItem

Get-Item

New-Item

Remove-Item

Move-Item

Rename-Item

Get-ItemProperty

Set-ItemProperty

Clear-ItemProperty

Get-ACL

Set-ACL

Objects can be searched, added, deleted or modified using Active Directory cmdlets, which will be covered in the later sections of the module.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 249 of 361

Exercise 3: Cmdlets and Identity Scenario The Active Directory module cmdlets can be used to perform various administrative, configuration, and diagnostic tasks in your AD DS environments. The Active Directory module can also be used to manage the existing Active Directory user and computer accounts, groups, organizational units (OUs), domains and forests, domain controllers, and password policies, or to create new ones. To list all the cmdlets that are available in the Active Directory module run the following command Get-Command –module ActiveDirectory

The Active Directory cmdlets can be used to retrieve information, add, create, delete, move, rename, reset, restore, search objects, set properties, enable or disable objects and features and unlock accounts. A group of tasks can be completed using the cmdlets to manage the following: 

Account Management



Group Management



Managed Service Accounts



Organizational Units



Password Policies



Optional Features



Search\Modify Objects



Forest and Domain Management



Domain Controller



Operations Master Management

Task 1: Connecting to the local domain 1. The command to get the local ADDomain object by using your current credentials is: PS AD:\> Get-ADDomain

Task 2: Connecting to the Global Catalog 2. To connect to a specific domain controller or port, you can use the -Server parameter. For instance, the following will retrieve all users found in the Global Catalog on SYDDC01: PS AD:\> Get-ADUser –Filter * -server syddc01.constoso.com:3268

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 250 of 361

Task 3: Miscellaneous Operations 3. Get all the members of the 'Schema Admins' group including the members of any nested groups. get-adgroupmember "Schema Admins" -recursive

4. Create a new user named 'Tkim' and set the EmployeeID and mail attributes. New-ADUser tkim –OtherAttributes @{employeeid="12345";mail="[email protected]"}

Task 4: Identity Parameter Almost all of the Active Directory cmdlets have an identity parameter for targeting a single Active Directory object. This parameter can also be used as the first positional argument for quick use. For each object type, the identity parameter searches a set of attributes to find a single match. If for some reason more than one object is found, an error will be returned. The following table covers some of the attributes searched when you specify the identity parameter: Cmdlet Noun ADComputer

ADDomain

ADDomainController

Attributes Searched for Identity                   

ADForest

ADGroup

Microsoft | Services

   

Distinguished Name GUID (objectGUID) Security Identifier (objectSid) Security Accounts Manager Account Name (sAMAccountName) Distinguished Name GUID (objectGUID) Security Identifier (objectSid) DNS domain name NetBIOS domain name GUID (objectGUID) IPV4Address Global IPV6Address DNS Host Name (dNSHostName) Name of the server object Distinguished Name of the NTDS Settings object Distinguished Name of the server object that represents the domain controller GUID of NTDS settings object under the configuration partition GUID of server object under the configuration partition Distinguished Name of the computer object that represents the domain controller Fully qualified domain name (FQDN) DNS host name NetBIOS name Distinguished Name

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 251 of 361

ADUser

ADObject ADOrganizationalUnit

          

GUID (objectGUID) Security Identifier (objectSid) SAM User Name (sAMUserName) Distinguished Name GUID (objectGUID) Security Identifier (objectSid) SAM User Name (sAMUserName) Distinguished Name GUID (objectGUID) Distinguished Name GUID (objectGUID)

1. The following examples show how the identity parameter is used to retrieve a specific user by using different attributes: #match on SamAccountName PS Contoso:\> Get-ADUser -Identity "tkim"

#SID PS Contoso:\> Get-ADUser -Identity "S-1-5-21-1989273325-1845373034-100956730-1604"

#DistinguishedName PS Contoso:\> Get-ADUser "CN=tkim,OU=test1,DC=contoso,DC=com"

#ObjectGUID PS Contoso:\> Get-ADUser "fc1afcab-5c3a-400a-9d91-16431452111b"

Note: The SID and GUID used in the examples above may not match your lab environment.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 252 of 361

Exercise 4: Searching Active Directory using Cmdlets Scenario The Active Directory cmdlets with the Verb ‘Get’ are used to search or enumerate objects from Active Directory.

Task Description 1. Type the following commands to list the cmdlets used to search AD object(s) of various classes. PS Contoso:\> gcm get-ad* | ft name Name ---Get-ADAccountAuthorizationGroup Get-ADAccountResultantPasswordReplicationPolicy Get-ADComputer Get-ADComputerServiceAccount Get-ADDefaultDomainPasswordPolicy Get-ADDomain Get-ADDomainController Get-ADDomainControllerPasswordReplicationPolicy Get-ADDomainControllerPasswordReplicationPolicyUsage Get-ADFineGrainedPasswordPolicy Get-ADFineGrainedPasswordPolicySubject Get-ADForest Get-ADGroup Get-ADGroupMember Get-ADObject Get-ADOptionalFeature Get-ADOrganizationalUnit Get-ADPrincipalGroupMembership Get-ADRootDSE Get-ADServiceAccount Get-ADUser Get-ADUserResultantPasswordPolicy

2. In the previous exercise, you have discussed about retrieving object information using the Identity parameter. For example: Get-ADUser -Identity tkim

In order to search the Active Directory based on a pattern or criteria, using an appropriate filter syntax becomes important. You can use the Filter or LDAPFilter parameter to specify a query string that retrieves Active Directory objects. In addition, certain parameters such as ResultPageSize, SearchBase or SearchScope can be used to search the Active Directory efficiently. 3. The following command gets all the Security groups that have a Group Scope of DomainLocal in the OU named Test1. get-adgroup -Filter 'GroupCategory -eq "Security" -and GroupScope -eq "DomainLocal"' –SearchBase ‘OU=Test1,dc=contoso,dc=com’

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 253 of 361

4. In order to search objects in the ‘Deleted Objects’ container, use the IncludeDeletedObjects parameter as shown below. Get-ADObject -Filter 'samaccountname -like "Vendor*"' -IncludeDeletedObjects

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 254 of 361

Exercise 5: Creating Active Directory Objects using Cmdlets Objectives In this exercise, you will explore some of the Active Directory cmdlets used to create objects.

Task Description 1. In your PowerShell console, type the following commands to get the cmdlets used to create new AD objects of various classes. PS Contoso:\> gcm new-ad* -commandtype cmdlet | ft name Name ---New-ADComputer New-ADFineGrainedPasswordPolicy New-ADGroup New-ADObject New-ADOrganizationalUnit New-ADServiceAccount New-ADUser

2. To create new users, you can use the New-ADUser cmdlet, as shown in the following example: PS Contoso:\> $pass = ConvertTo-SecureString "P@ssword1" -AsPlainText –Force PS Contoso:\>New-ADUser -SamAccountName "Dpark" -Name "Dan Park" ` -GivenName "Dan" -Surname "Park" ` -Department "IT" -AccountPassword $pass ` -UserPrincipalName "[email protected]"

The ConvertTo-SecureString cmdlet shown above creates a secure string which is needed to specify the User Account password. 3. Consider another scenario where you will create a list of users from a CSV file. The column headers in the CSV file may or may not match the Active Directory attribute names used by New-ADUser cmdlet. For instance, if the column headers are “GivenName”, “Surname,” “Title,” “Department,” “EmployeeId”, “Mail” and so on, or assuming that after receiving the CSV file you modified the column headers to match the attribute names, the following command will create bulk users. PS Contoso:\>Import-CSV c:\pshell\part1\lesson8\userlist.csv | New-ADUser

4. If the column headers do not match the attribute names, the cmdlet Select-Object can be used to calculate the properties as shown in the following example. PS Contoso:\>Import-CSV c:\pshell\part1\lesson8\userlist.csv | Select ` @{Name="GivenName";Expression={$_."First Name"}}, ` @{Name="Surname";Expression={$_."Last Name"}}, `

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 255 of 361

@{Name="Title";Expression={$_."Job Title"}}, ` @{Name="Department";Expression={$_.Section}}, ` @{Name="Employeeid";Expression={$_."Employee ID"}} | New-ADUser

5. Now explore the cmdlet New-ADGroup to create a new group named 'Managers' in the container 'CN=Users,DC=Contoso,DC=Com' and set the GroupCategory, DisplayName, GroupScope, and Description properties on the new object. C:\PS>New-ADGroup -Name "Managers" -SamAccountName Managers -GroupCategory Security -GroupScope Global -DisplayName "Managers" -Path "CN=Users,DC=Contoso,DC=Com" -Description "Members of this group are floor Managers”

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 256 of 361

Exercise 6: Modifying Objects using Cmdlets Scenario Now that you are familiar with cmdlets used to search and create objects, you can explore some of the Active Directory cmdlets used to modify existing AD objects.

Task Description 1. In your PowerShell console, type the following command to get the cmdlets used to modify AD objects of various classes. PS Contoso:\> gcm set-ad* -commandtype cmdlet | ft name Name ---Set-ADAccountControl Set-ADAccountExpiration Set-ADAccountPassword Set-ADComputer Set-ADDefaultDomainPasswordPolicy Set-ADDomain Set-ADDomainMode Set-ADFineGrainedPasswordPolicy Set-ADForest Set-ADForestMode Set-ADGroup Set-ADObject Set-ADOrganizationalUnit Set-ADServiceAccount Set-ADUser

2. A simple example shown below updates the company and department attributes on a single target identity. Set-ADUser Dpark -Company ‘Contoso’ -Department 'Sales'

Bulk Modifications You might encounter scenarios with many users in an environment, who do not have a UserPrincialName (UPN) configured. In these scenarios, you can use Get-ADUser to search for users without a UPN and pipe the results to Set-ADUser to modify the user accounts. 3. If you simply want to set the user account to be the sAMAccountName with the domain suffix, you can use a command similar to the one shown below: Get-ADUser -filter {UserPrincipalname -notlike "*"} | ForEach-Object {Set-ADuser Identity $_ -UserPrincipalName "$($_.sAMAccountName)@contoso.com"}

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 257 of 361

Exercise 7: PowerShell Credential Objects and Using Alternative Credentials for Cmdlets Scenario The Active Directory cmdlets have the Credential parameter to use alternate credentials to perform a task in the current session. The default credentials are the credentials of the currently logged-on user, unless the cmdlet is run with the account associated with an Active Directory PowerShell provider drive. To specify this parameter, you can type a user name, such as "Contoso\User01" or you can specify a PSCredential object.

Task Description 1. If you specify a user name for this parameter, the cmdlet prompts for a password. Get-ADComputer –filter ‘samaccountname –notlike “syd*”’ –searchbase ‘OU=Domain Controllers,DC=contoso,dc=com’ -credential contoso\administrator

2. You can also create a PSCredential object by using a script or by using the GetCredential cmdlet. You can then set the Credential parameter to the PSCredential object. 3. The following example shows how to create credentials. $DomainCreds = Get-Credential "Contoso\administrator"

4. The following shows how to set the Credential parameter to these credentials. Get-ADuser –Identity tkim -Credential $DomainCreds

5. Often, when using alternate credentials or specifying specific server connection settings, it can become tedious to specify these parameters for every cmdlet being used. In addition, each time you specify these parameters, a new session is set up, which has some performance costs associated with it. A better approach is to use the Active Directory PSProvider to create a PSDrive, which connects to the Active Directory. New-PSDrive -PSProvider ActiveDirectory -Name Contoso -Root ` "AD:\dc=contoso,dc=com" –credential $DomainCreds

The syntax shown above creates a PSdrive named Contoso connected with the credentials specified in the DomainCreds variable.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 258 of 361

Lesson 8 Hands-On : Active Directory Administration (cmdlets) Objectives The objective for this lab is to explore creating, modifying and searching Active directory objects using the Windows PowerShell Active Directory Cmdlets.

Prerequisites The lab requires a windows 7 client running in a domain environment.

Estimated time to complete this lab 30 minutes

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 259 of 361

Exercise 1: Creating Multiple Users in an Organizational Unit Objectives In this exercise, you will: 

Create an Organizational Unit (OU)



Create nine temporary user accounts in the OU using concatenation



Specify certain attribute values for the users from a text file, populate those on the General, Address and Profile tabs

Scenario The AD administrator of Contoso Limited receives a request for creating lab users for their development work. The users belong to the same physical location, hence a common address. In addition to the name, surname, UPN and e-mail address attributes, the users would also have a home directory and roaming profile stored on the respective shares on the server Syddc01. The administrator will have to automate the user creation using the Active Directory modules for Windows PowerShell.

Duration 10 minutes

Task 1: Develop a script that will create AD Objects 1. Log on to the VM environment: Log on to Windows 7 Enterprise client as Contoso\Administrator with Password P@ssword 2. Open Notepad or another script editor 3. Open the file c:\pshell\part1\lesson8\lab8\address.txt. This file contains the address details that will be used for the test users. 4. Create a new file in the ISE or notepad and save it as c:\pshell\part1\lesson8\labs\lab8ex1.ps1 5. For the first line of the file enter the following code $error.clear()

This will ensure that only errors related to the script are reported. 6. Type the following line to load the Active Directory module. Import-module activedirectory

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 260 of 361

7. In order to create an OU named “LabUsers” in which the users will be created, type the following line New-ADOrganizationalUnit -Name LabUsers -Path "DC=CONTOSO,DC=COM”

8. Type the following code for the next line of the script $aryText = Get-Content -Path "c:\pshell\part1\lesson8\labs\address.txt"

This will load the address details from the file that will be used for the user accounts. 9. On the next line, type the following code to create a variable for the username prefix. $Username = "LabUser"

10. On the next line, type the following code to create the variable for the max user count. $intUsers = 9

11. On the next line, type the following code to create a variable for the user path. $userpath = "OU=LabUsers,DC=contoso,DC=com"

12. On the next line, type the following code on the next line to start the for loop. for ($i=1; $i -le $intUsers; $i++)

13. On the next line, type the following code to open the script block. {

14. On the next line, type the following code to create each user account with the attributes to be populated in the General, Address and Profile tabs. new-aduser -name $username$i -samaccountname $username$i -path $userpath ` -displayname "$username$i" -givenname "$username$i" -surname "surname" ` -Initials $i -Description $($aryText[0]) ` -UserPrincipalName "[email protected]" ` -EmailAddress "[email protected]" -StreetAddress "$($aryText[1])" ` -city "$($aryText[2])" -state "$($aryText[3])" -PostalCode "$($aryText[4])" ` -OfficePhone "02-$i$i$i$i-$i$i$i$i" ` -ProfilePath "\\syddc01\users\$username$i" -HomeDrive "h" ` -HomeDirectory "\\syddc01\userdata\$username$i"

15. On the next line, type the following code to close out the For loop. }

16. Now save the script. 17. Launch “Windows PowerShell” session. 18. In the PowerShell console, type the following to execute the script. c:\pshell\part1\lesson8\labs\lab8-ex1.ps1

The script should execute and create the users and populate the user properties. 19. In ADUC, check for the users in the LabUsers OU.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 261 of 361

20. Check one of the users property tabs. You will see that the user properties have been populated.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 262 of 361

Exercise 2: Modifying AD objects via Cmdlets Objectives In this exercise, you will: 

Modify the attributes of existing users using the Set-ADuser cmdlet



Perform a bulk deletion of the lab users

Scenario The Contoso management requires redeployment of first five lab users to a different development project. From now on, those lab users will be located at a different office. The AD administrator requires to automate the change of address details using the Active Directory modules for Windows PowerShell.

Duration 10 minutes

Task 1: Develop a script to modify AD Objects 1. Log on to the VM environment: Log on to Windows 7 Enterprise client as Contoso\Administrator with Password P@ssword 2. Open Notepad or another script editor. 3. Open the file c:\pshell\part1\lesson8\labs\NewAddress.txt. This file contains the new address details of the relocated lab users. 4. Create a new file in the ISE or notepad and save it as c:\pshell\part1\lesson8\labs\lab8ex2.ps1 5. For the first line of the file, enter the following code. $error.clear()

This will ensure that only errors related to the script are reported. 6. Type the following line to load the Active Directory module. Import-module activedirectory

7. Type the following code for the next line of the script. $aryText = Get-Content -Path "c:\pshell\part1\lesson8\labs\NewAddress.txt"

This will load the address details from the file that will be used to change or update the address details of the user accounts. 8. On the next line, type the following code to create a variable for the username prefix. $Username = "LabUser"

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 263 of 361

9. On the next line, type the following code to create the variable for the max user count to be modified. $intUsers = 5

10. On the next line, type the following code on the next line to start the For loop. for ($i=1; $i -le $intUsers; $i++)

11. On the next line, type the following code to open the script block. {

12. On the next line, type the following code to modify the target user accounts’ address details. set-aduser -identity $username$i -StreetAddress "$($aryText[0])" ` -city "$($aryText[1])" -state "$($aryText[2])" -PostalCode "$($aryText[3])"

13. On the next line, type the following code to close out the For loop. }

14. Now save the script. 15. Launch “Windows PowerShell” session. 16. In the PowerShell console, type the following to execute the script. c:\pshell\part1\lesson8\labs\lab8-ex2.ps1

The script should execute and modify the users’ address details. In ADUC, refresh the view and check for the users in the OU. 17. Check one of the users Address property tab. You will see that the user properties have been modified. 18. Open the script c:\pshell\part1\lesson8\lab8\lab8-ex2.ps1 and save it as c:\pshell\part1\lesson8\lab8\lab8-ex2a.ps1 19. Now delete the following lines of code from the script. set-aduser -identity $username$i -StreetAddress "$($aryText[0])" ` -city "$($aryText[1])" -state "$($aryText[2])" -PostalCode "$($aryText[3])"

20. Now type the following code between the { and } lines Remove-aduser -Identity "$username$i"

21. Save the script. 22. The new script will now delete the lab user accounts from Active Directory. 23. In the PowerShell console, type the following to execute the script. c:\pshell\part1\lesson8\lab8\lab8-ex2a.ps1

The script should execute and delete the users.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 264 of 361

Exercise 3: Searching AD objects via Cmdlets Objectives In this exercise, you will: 

Search Active Directory based on a filter syntax



Use the cmdlet Get-AdUser

Scenario During an Active Directory disaster recovery exercise, Contoso DR management team expressed the requirement to have a script that would populate all the objects that have been deleted in the last seven days. The AD administrator will need to write the script that will search the Deleted Objects container and list the objects deleted in the last seven days.

Duration 10 minutes

Task 1: Find AD Objects deleted in the past 7 days 1. Log on to the VM environment: Log on to on to Windows 7 Enterprise client as Contoso\Administrator with Password P@ssword 2. Open Notepad or another script editor. 3. Create a file named c:\pshell\part1\lesson8\labs\lab8-ex3.ps1 in notepad or the PowerShell ISE and save it. 4. For the first line of the file, after the comment section (#), enter the following code. $error.clear()

This will ensure that only errors related to the script are reported. 5. Type the following line to load the Active Directory module. Import-module activedirectory

6. Type the following code for the next line of the script to specify the CSV file path to which the output will be exported. $csvpath = "c:\pshell\part1\lesson8\labs\deletedobjects.csv"

7. On the next line, type the following code to create a variable to store the datetime (current date – 7 days) object. $deletedindays = (get-date).adddays("-7")

8. On the next line, type the following code to create the variable for the search filter string. $searchfilter= 'isdeleted -eq $true -and whenchanged -gt $deletedindays'

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 265 of 361

The filter above would search for objects that have their IsDeleted attribute set to True and the whenchanged attribute is within the last 7 days. 9. On the next line, type the following code to search AD according to the filter string (including the Deleted Objects container) and store the result in the designated CSV file. Get-ADObject -Filter $searchfilter -IncludeDeletedObjects | select name,objectclass | export-csv -Path $csvpath -notypeinformation

10. Now save the script. 11. Launch “Windows PowerShell” session. 12. In the PowerShell console, type the following to execute the script. c:\pshell\part1\lesson8\labs\lab8-ex3.ps1

The script should execute and search the deleted objects. 13. Open the CSV file "c:\pshell\part1\lesson8\lab8\deletedobjects.csv" and check for the desired results. notepad "c:\pshell\part1\lesson8\labs\deletedobjects.csv"

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 266 of 361

PowerShell for the IT Administrator, Part 1 Lesson 9: Windows Management Instrumentation

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Lesson 9 Demonstration : Windows Management Instrumentation (WMI) Introduction In this section, you will cover the core concepts of Windows Management Instrumentation, better known as ‘WMI’. These concepts include working with classes, gathering data both locally and remotely as well as real-world applications.

Objectives After completing this lab, you will be able to: 

Describe the core WMI concepts in Windows



Leverage the Get-WMIObject cmdlet to access WMI from within PowerShell



Review some of the most commonly used WMI classes



Discover gathering data remotely using Get-WMIObject



Filter and sort returned WMI data



Provide best practices when leveraging WMI in scripting

Prerequisites 

A Windows 7 workstation logged in with administrator credentials



A Windows 2008 server logged in with administrator credentials

Estimated time to complete this lab 60 minutes

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 268 of 361

Exercise 1: Introduction to WMI Objectives In this exercise, you will: 

Learn the fundamentals of WMI.



Identify the basic WMI components and related tools in Windows.



Understand basic information related to the service.

Scenario WMI is an integral part of Windows infrastructure and is installed by default. In this scenario, we will explore the WMI Management console and underlying services.

Task 1: Log on to the VM environment Log on to Windows 7 Enterprise client as: 

Username: Contoso\Administrator



Password: P@ssword

Task 2: Open Windows PowerShell On the Windows taskbar, click

.

The PowerShell console opens.

Concepts of Instrumentation Instrumentation is the act of making data available through an avenue of communication. In programming terms, that translates to being able to gather trace information, performance data or verbose error logging. Instrumentation can be fully understood in a more familiar context. Consider an automobile. When we want to know the status of a vehicle's component, we rely on instrumentation to do it. Since we cannot “speak” directly to the car, we have to use an infrastructure that allows communication. The gauge on the dashboard interacts with various sensors throughout the vehicle and translates data, allowing you to see various conditions (such as current speed and fuel level). Hardware (Engine)

Data Translation (Gauge)

Raw data

Object

User readable

Instrumentation in Windows is very similar. It allows drivers and components to output data that can then be used by users or other processes. This effectively allows us to “speak” to deeper layers of the OS and hardware.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 269 of 361

WMI Organization WMI is built around the concepts of Classes, Instances and Namespaces. A Class is essentially anything WMI can manage. It is a template for an underlying object and describes its function. All objects of each Class follow the same basic layout; however, the actual data they contain is unique to that object. Common Class Types Hardware Classes Software Classes Operating System Classes Performance Counter Classes

Describe Hardware events/data (static) Describe Software events/data (dynamic) Describe OS specific information Describe Performance data (Perfmon) counters

An Instance represents the objects within each class. Each object follows a template described by the parent Class in which it resides. Namespaces are logical groupings of Classes.

Namespace

WMI Class

Object Instance

WMI Class

Object Instance

Object Instance

Object Instance

All content for WMI resides in a database known as a Repository. The default Repository location in Windows is: %Systemroot%\WBEM\Repository

Task 3: Work with WMI: Control Console 1. Click Start > Run, and type the following command: WMIMGMT.MSC

2. Explore the WMI tabs for information. From this pane, you can gather basic information such as location of WMI repository on disk, WMI revision and Security information.

Task 4: Inspect the WMI Services 1. Using SC.EXE from the Command line to gather service information, you can see several key pieces of data on the WMI management service: C:\> sc.exe qc winmgmt SERVICE_NAME: winmgmt TYPE

Microsoft | Services

: 20

WIN32_SHARE_PROCESS

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 270 of 361

START_TYPE ERROR_CONTROL BINARY_PATH_NAME LOAD_ORDER_GROUP TAG DISPLAY_NAME DEPENDENCIES SERVICE_START_NAME

: : : : : : : :

2 AUTO_START 0 IGNORE C:\Windows\system32\svchost.exe -k netsvcs 0 Windows Management Instrumentation RPCSS localSystem

C:\> sc.exe query winmgmt SERVICE_NAME: winmgmt TYPE STATE

: 20 WIN32_SHARE_PROCESS : 4 RUNNING (STOPPABLE, PAUSABLE, ACCEPTS_SHUTDOWN) : 0 (0x0) : 0 (0x0) : 0x0 : 0x0

WIN32_EXIT_CODE SERVICE_EXIT_CODE CHECKPOINT WAIT_HINT

2. Using PowerShell’s Get-Service Cmdlet to query the service information: PS> get-service winmgmt | format-list *

Name : RequiredServices : CanPauseAndContinue : True CanShutdown : CanStop : DisplayName : Windows DependentServices : MachineName : . ServiceName : ServicesDependedOn : ServiceHandle : Status : ServiceType : Site : Container :

winmgmt {RPCSS} True True Management Instrumentation {WinTarget, vmms, vhdsvc, SharedAccess...} winmgmt {RPCSS} SafeServiceHandle Running Win32ShareProcess

The PowerShell output varies slightly from the SC.EXE returned information.

Task 5: List WMI Namespaces 1. In the PowerShell console, type the following command to list the WMI namespaces. Get-wmiobject –class __namespace –namespace root | select name

You will now see a list of the available namespaces in the WMI repository from the root. This, however, is only the top layer of the available namespaces. There are subnamespaces available but the command above does not display them. 2. In the PowerShell console, run the script recurse-namespaces.ps1

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 271 of 361

This script will display all the namespaces and sub-namespaces available for the current machine. For almost all purposes, you will use the root\cimv2 namespace. function searchns($ns) { write-host $ns -foregroundcolor white $colns = get-wmiobject -namespace $ns -class "__namespace" if ($colns -ne $null) { foreach ($i in $colns) { $subns = $i.__namespace+"\"+$i.name searchns($subns) } } } Write-host "The Following are all the namespaces and sub namespaces in `n WMI on the local machine" -foregroundcolor green searchns("root")

This script will now display the full list of available WMI namespaces and sub-name spaces. You will notice that there are many available namespaces and sub-namespaces.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 272 of 361

Exercise 2: WMI Classes and Queries Now you will explore the types of data that can be returned from WMI via PowerShell. The primary and most common cmdlet for accessing WMI data is the Get-WmiObject commandlet. From this point forward, you will be primarily working with this commandlet and the subset of returned data. However, before looking into the cmdlet you need to list the available classes for a given namespace.

Task 1: List Available Classes 1. From the PowerShell console, type the following to list the available classes. Get-wmiobject -list

You will now see a list of the available WMI classes for the root\cimv2 namespace. Root\cimv2 is the default namespace used by WMI. This default namespace is used by the get-wmiobject Cmdlet if you do not specify it. 2. Type the following to display only the names of the WMI classes. Get-wmiobject –list | select name

Task 2: Understand WMI Metadata You will notice that in addition to the normal WMI classes, you also have metadata classes. Metadata is information about WMI. This could be: 

Data about namespaces or classes



Other WMI information such as configuration



Additional information about a WMI class such as its superclass

The WMI metadata is visible as anything that starts with a double underscore or __. This makes it easy to filter as you can look for anything that does not start with __. 1. Type the following in the PowerShell console to filter out the metadata classes. Get-wmiobject –list | where-object {$_.name –like win32_*}

As you can see from the output, this displays all the properties of the class without the metadata. You can use the range wildcard to out the metadata for all WMI classes and other queries.

Task 3: Understand the Get-WMIObject Cmdlet The get-wmiobject cmdlet is the cmdlet that allows us easy access to WMI data from within PowerShell. This cmdlet allows for very simple access to local WMI data, as well as more complex access such as remoting and WMI queries. This cmdlet has been available from PowerShell version 1 and at that time was one of the few cmdlets that supported remote data collection. In PowerShell 2.0, the ability to use WMI as a background job as well as the ability to use WMI events. 2. From within the PowerShell console, inspect what the get-wmiobject cmdtlet can do Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 273 of 361

Get-Help Get-WmiObject -examples

1. From the examples, it appears that the get-wmiobject cmdlet can return a wide variety of data from WMI objects. Now, perform a basic query on a Logical Disk Class. Get-WmiObject –Class “Win32_LogicalDisk”

DeviceID DriveType ProviderName FreeSpace Size VolumeName

: : : : : :

C: 3

DeviceID DriveType ProviderName FreeSpace Size VolumeName

: E: : 5 : : : :

87575044096 497958252544 Windows 7

You will notice that in this query, the namespace is not specified. PowerShell will use: 

The default WMI scripting namespace defined via the WMI control console, or



What is defined in the registry key HKLM:\Software\Microsoft\WBEM\Scripting Default namespace

From this simple query, you can gather some useful information related to the current diskrelated hardware on the machine. The first entry lists the DeviceID “C:” and a DriveType of 3. There are other fields designating metrics such as Total Size and Volume Name. The second entry had a DeviceID of “E:” and has a different DriveType of 5. Note that there is no data for other fields. DriveType Reference # Type: -------------------------------------------------------------------------------------------------------------1 No Root Directory 2 Removable Disk 3 Local Disk 4 Network Drive 5 Compact Disc 6 RAM Disk

From this quick data collection, you can infer that “C” is a Hard Disk approximately 500Gigabytes in size, while “E” is a CD/DVD unit with no media loaded. For further details, you can use the WMI SDK file reference that is on the desktop of the workstation. The file is WMISKD_School.chm. You can find details for every WMI class in the MSDN documentation website.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 274 of 361

Now, expanding on that concept, look at the Win32_Bios class and see what data can be gathered about the machine: PS> Get-WmiObject –Class Win32_Bios

SMBIOSBIOSVersion Manufacturer Name SerialNumber Version

: : : : :

090004 American Megatrends Inc. BIOS Date: 03/19/09 22:51:32 Ver: 09.00.04 0654-6116-5806-0058-2049-6801-11 VRTUAL - 3000919

This returned only a small portion of the available data held in the Win32_Bios class. To get the full output, pipe the contents to a Format-List. Get-WmiObject –class Win32_Bios | fl *

You will see here that the WMI metadata is also returned. To filter this metadata out, you can use the a-z range wildcard. Type the following to filter out the metadata and display only the properties for the class. Get-wmiobject –class win32_bios | format-list [a-g]*

In some cases, other cmdlets use WMI to return data (although often filtered in some fashion). Now, compare the output from Get-Service to Get-WmiObject against the Netlogon service: Get-wmiobject Win32_Service| ?{$_.name –eq “netlogon”} | fl * Name Status ExitCode DesktopInteract ErrorControl PathName ServiceType StartMode AcceptPause AcceptStop Caption CheckPoint CreationClassName

: : : : : : : : : : : : :

Netlogon OK 1077 False Normal C:\Windows\system32\lsass.exe Share Process Manual False False Netlogon 0 Win32_Service

Description : Maintains a secure channel between this computer and the domain controller for authenticating users and services. If this service is stopped, the computer may not authenticate users and records. If this service is disabled,any services that explicitly depend on it will fail to start. DisplayName InstallDate ProcessId ServiceSpecificExitCode Started StartName State SystemCreationClassName

Microsoft | Services

: : : : : : : :

Netlogon 0 0 False LocalSystem Stopped Win32_ComputerSystem

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 275 of 361

SystemName TagId WaitHint Scope Path Options ClassPath Properties SystemProperties Qualifiers

: : : : : : : : : :

CONTOSO 0 0 System.Management.ManagementScope \\CONTOSO\root\cimv2:Win32_Service.Name="Netlogon" System.Management.ObjectGetOptions \\CONTOSO\root\cimv2:Win32_Service {AcceptPause, AcceptStop, Caption, CheckPoint...} {__GENUS, __CLASS, __SUPERCLASS, __DYNASTY...} {dynamic, Locale, provider, UUID}

get-service netlogon | fl *

Name RequiredServices CanPauseAndContinue CanShutdown CanStop DisplayName DependentServices MachineName ServiceName ServicesDependedOn ServiceHandle Status ServiceType Site Container

: : : : : : : : : : : : : : :

Netlogon {LanmanWorkstation} False False False netlogon {} . Netlogon {LanmanWorkstation} SafeServiceHandle Stopped Win32ShareProcess

Both methods of access return data related to services, but the WMI object directly is far more verbose. To find out what other Classes are available to us, use the Get-WmiObject cmdlet to return an entire list (this may take a minute to enumerate depending on machine speed). PS:> Get-WmiObject -list

As you can see, there are more than a thousand default/base classes available for a wide range of components. Additional classes are often included for different product lines such as SharePoint, IIS and Exchange. If you need information on methods, this code snippet will query WMI and extract all the available methods for all classes. PS:> Get-WmiObject -List * | Where-Object{$_.Methods -ne $Null} | Select-Object -ExpandProperty Methods | Sort-Object Origin,Name | Select-Object Origin,Name -Unique

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 276 of 361

Task 4: Understand Get-wmiobject Parameters The get-WMIObject cmdlet has additional parameters that are very useful since they can be used to significantly change the behavior of the cmdlet . Some of these make it clear as to what the cmdlet is operating on, while others can change the type of query used by the cmdlet or what credentials or impersonation level the query is run as. Not all parameters will be covered, but some of the important ones that you should be aware of will be. -namespace Parameter The first parameter you will look at is the -namespace. This optional parameter is used to specify the namespace to query. In WMI, you always have to query a namespace; however, for most purposes the default namespace of root\cimv2 is used. In fact, if you do not specify a namespace this is the namespace that will be used. You can test this with the following examples:

1. In the PowerShell console, type the following command and press Enter. Get-wmiobject win32_computersystem

You will see that the information for win32_computer system is displayed. 2. In the PowerShell console, type the following command and press Enter. Get-wmiobject –namespace root\cimv2 win32_computersystem

You will see that the information for win32_computer system is displayed. This is the same as the information displayed when not specifying the namespace. This information is important for two main reasons. 

Although most of the information you will be working with will come from root\cimv2, there are times that you may need to get information from other namespaces. An example of this is the System Center Configuration Manager client agent. The Client agent has its own WMI namespace, which can be used to trigger client agent actions such as check for advertisements or perform software or hardware inventory.



The other reason you should know about the -namespace parameter is because the default namespace on the machine might change. While this is rare, if you are writing scripts that rely on the default value and never check it or explicitly specify it, your code could have errors. It is good practice to always specify the namespace in scripts, to ensure you are addressing the correct namespace.

-class Parameter The class parameter is a required parameter and the default parameter. This means that the first value passed to the cmdlet will, by default, be assigned to the class parameter. The class is the WMI class that you wish to obtain information from. For example, the following are the same command: Get-wmiobject win32_process Get-wmiobject –class win32_process

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 277 of 361

Similarly, always specifying the namespace parameter in scripts, is also a good practice to specify the class parameter. This does not always apply to interactive console use, as it is important to minimize the amount of typing done in the PowerShell console. However, the parameter should always be used in scripts. So, for example, the following should be used in a PowerShell script. Get-wmiobject –namespace “root\cimv2” –class win32_process

-list Parameter The -list parameter is used to list the available classes for a given namespace. If the namespace is not specified then the default name space of root\cimv2 is used. -computer Parameter The -computer parameter is used to specify the computer to be queried. The parameter is optional and the local computer is used unless specified otherwise. In the WMI query language (WQL) that will be covered shortly, the local computer is referred to as a . You can specify the parameter and use the . to ensure you are working against the local computer or you can specify the NetBIOS, FQDN or even IP address of a remote machine to query.

For example, Get-wmiobject –computer syddc01 –namespace root\cimv2 –class win32_share

-credential Parameter Like several other cmdlets , the -credential parameter is used to allow the get-wmiobject cmdlet to be run as another account. This parameter requires a PowerShell credential object. If specified with the username, it will prompt for the password. This is typically used when also specifying the -computername parameter.

For example, $creds = get-credential Get-wmiobject –computer syddc01 –namespace root\cimv2 –class win32_share –credential $creds

-EnableAllPrivileges Parameter The -EnableAllPrivileges parameter is used to enable all privileges for the current user. This is sometimes needed, as some special WMI privileges are used with some methods that are not normally granted by default. The best example of this is the shutdown computer right. If the -EnableAllPrivileges parameter is not specified, calling the method will fail.

Task 5: Understand Queries using WQL WMI contains its own query language, called WMI query language and WQL for short. This language allows complex SQL-like queries to be run against a class or collection of classes to return specific data. However, WQL is not a complete T-SQL language and is instead a limited subset of T-SQL. As a result, WQL only supports fairly simple queries and limited keywords. The more complex programing statements of T-SQL are not available (such as if

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 278 of 361

statements). If you reference the WMI SDK and look for the topic on WQL, you will find the full list of keywords and operators available for WQL. The basic structure of a WQL query is very similar to SQL. | properties | | class | | filter criteria The first two sections, the select and from are mandatory. The where section is optional.

The select Section The select section can be used to retrieve only properties of interest. This is done by specifying the names of these properties. If multiple properties are required, they can be separated by a comma. This has an impact on the amount of data retrieved and transmitted (for remote queries). It is a good practice to retrieve only information of interest. It is acceptable to use select * if you want all the properties of a class or instance. It is also useful when testing a query or if you do not know what properties are available. However, for the verified queries, only the information of interest should be retrieved. For example, Get-WmiObject –Query “Select name, startmode, state from win32_service” | format -list *

You will notice that even though only the name, startmode and state properties have been selected, using the format-list Cmdlet displays these properties as well as the WMI metadata as the __ classes. This is unavoidable, as the WMI service will always return the metadata. This can be dealt with in two ways. 

It can be filtered from display using format-list [a-z]*. However, the data is still there.



It can be discarded by using the select-object Cmdlet and specifying the properties of interest.

The from Section The from section is the simplest section of the query. This is the name of the WMI class to query.

The where Section. The where section is used to: 

Select a WMI instance of interest, or



Check if a WMI instance matches a criteria

This is similar to the where-object Cmdlet. However, it is much more powerful as the WMI service performs the filtering. In our example above, using a Get-WMIObject against the Service class returns all objects. You can then filter them using the Where-Object Cmdlet.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 279 of 361

Get-wmiobject Win32_Service| where-object {$_.name –eq “netlogon”}This is effective but rather inefficient if you are concerned with very specific data. Now, using the WQL structure, you can issue the same query with more specific expected results: Get-WmiObject –Query ‘Select * from win32_service where name=”netlogon”’

Note the use of the double quotes inside the single quote string. This is due to the way the Cmdlet and the query works. The reason for this is that the query needs to be a string in PowerShell, while the query is actually a command for the WMI service. As such, the value of netlogon needs to be passed to the WMI service as a string. The use of the double quotes inside the single quotes allows for a string inside a string. It is also possible to use this in the opposite way and have single quotes inside a double quote string. The latter is more common as it allows for variables to be used and expanded inside the query string. ExitCode Name ProcessId StartMode State Status

: : : : : :

0 Netlogon 604 Auto Running OK

Now, you are selectively targeting just the Netlogon service as part of the query. Only this object is returned rather than a collection of all objects. For a local query, the results will be very similar. However, there is an execution advantage in getting the WMI query to perform the filtering. This is because the WMI service will be performing the filtering. For a remote query, this is very important as the amount of data retrieved from the WMI service and then transmitted over the network is very different. The execution time is also affected. This is also very important in scripts, as you will often be retrieving WMI information from multiple machines. A major difference to be aware of when using WQL is the operators used in the where section. The operators used here are WQL operators and not PowerShell operators. The following are the WQL operators and their descriptions: Operator

Description

=

Equal to

<

Less than

>

Greater than

=

Greater than or equal to

!= or

Not equal to

Is

Is

Is not

Is not

Like

Wildcard match

There are two other things you need to be aware of with WQL, that are different from the PowerShell language:

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 280 of 361



Logic keywords in the where section



WQL wildcards

The WQL wildcards are below. These are used only in the where section. Character

Description

[]

Any one character within the specified range ([a=c]) or a set ([abcdefg])

^

Any one character not within the specified range ([^a=c]) or a set ([^abcdefg])

%

Any string of zero or more characters. Similar to *

_ or (underscore)

Any single character. Any literal underscore used in the query string must be escaped by placing it inside [] or square brackets

The logic keywords available for use in the WQL language are the words AND and OR as well round brackets (). The normal algebraic logic rules apply here, with both the use of the keywords and the brackets.

Using the -filter Parameter Get-WMIObject also supports the action of Filtering directly within the Cmdlet itself. Instead of using a WQL Select… statement, you can use the -filter parameter to access a property directly. This is a shortcut directly to the where section of the query and uses the WQL operators (not the PowerShell operators). In the example above, you retrieved service information on the Netlogon service. Now perform the same action, this time using the -filter parameter: gwmi win32_service -filter 'name = "netlogon"'

ExitCode Name ProcessId StartMode State Status

: : : : : :

0 Netlogon 604 Auto Running OK

We get the same data set returned in either scenario. Using the -filter criteria may be advantageous when only a small subset of data is desired (specific property) while the WQL query is more robust.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 281 of 361

Exercise 3: WMI Remoting and Method Execution Task 1: WMI Remoting The power of WMI really comes into play with gathering data from remote sources. In PowerShell the Get-WmiObject cmdlet is the main source of data retrieval. In the previous exercise, it was used to gather data from a single machine. The Get-WmiObject cmdlet supports the -ComputerName parameter. This means that, natively, the cmdlet is equipped to gather data remotely. Any WMI query that can be run locally can also be run remotely by adding the -ComputerName switch. Now you will use the Win32_Bios class to demonstrate the remote abilities: Get-WmiObject –Class Win32_Bios

SMBIOSBIOSVersion Manufacturer Name SerialNumber

: : : :

090006 American Megatrends Inc. BIOS Date: 05/23/12 17:15:53 Ver: 09.00.06 5841-1807-8159-8121-4504-5660-30

Version : VRTUAL - 5001223Use the same command, but now executed against a machine named syddc01 Get-WmiObject -Computername "syddc01" -Class Win32_Bios

SMBIOSBIOSVersion Manufacturer Name SerialNumber

: : : :

090006 American Megatrends Inc. BIOS Date: 05/23/12 17:15:53 Ver: 09.00.06 5661-8327-5168-3547-0914-4161-08

Version : VRTUAL - 5001223The data returned from the local (Virtual) machine differs from the data retrieved from the remote machine (in this case a different virtual machine with a different serial number).

Task 2: Method Execution Like all other objects available for use in PowerShell, WMI object also contains both properties and methods. These methods allow you to make configuration changes to system objects such as services or network cards, or schedule events such as a chkdsk. To expose the methods available for a WMI class, you can simply use the get-member cmdlet just like any other PowerShell object. 1. In the PowerShell console, type the following: get-wmiobject –namespace “root\cimv2” –class win32_service | get-member ` –membertype method | select name

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 282 of 361

TypeName: System.Management.ManagementObject#root\cimv2\Win32_Service Name ---Change ChangeStartMode Delete GetSecurityDescriptor InterrogateService PauseService ResumeService SetSecurityDescriptor StartService StopService UserControlService

MemberType Definition ---------- ---------Method Change(System.String DisplayName, System.Str... Method ChangeStartMode(System.String StartMode) Method Delete() Method GetSecurityDescriptor() Method InterrogateService() Method PauseService() Method ResumeService() Method SetSecurityDescriptor(System.Management.Mana... Method StartService() Method StopService() Method UserControlService(System.Byte ControlCode)

TypeName: System.Management.ManagementObject#root\cimv2\Win32_TerminalService Name ---Change ChangeStartMode Delete GetSecurityDescriptor InterrogateService PauseService ResumeService SetSecurityDescriptor StartService StopService UserControlService

MemberType Definition ---------- ---------Method Change(System.String DisplayName, System.Str... Method ChangeStartMode(System.String StartMode) Method Delete() Method GetSecurityDescriptor() Method InterrogateService() Method PauseService() Method ResumeService() Method SetSecurityDescriptor(System.Management.Mana... Method StartService() Method StopService() Method UserControlService(System.Byte ControlCode)

Note that the output has been modified for display purposes. As you can see from the output, using get-member you can easily display the methods available for a WMI class. To execute one of these methods, there are a few things you need to remember. First, for multiple instance classes, you need to isolate the results to a single instance to execute the method on. Second, you need to know how the method works. For each WMI class, and even each WMI method, these can be very different. Just like a .NET class, you will need to reference each WMI class and each method to know how they work. This is again in the WMI SDK. In the example above, you used the win32_service class, which contains an instance for each service on the system. For example, to be able to use the stopservice method, you need to target just one service. For this example, you will use the BITS server. 2. In the PowerShell console, type the following: $bits = get-wmiobject –namespace “root\cimv2” –class win32_service –filter ` “name=’bits’”

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 283 of 361

The code above assigns the BITS service object to the variable $bits, which allows you to execute the method using the dot notation. You can do this as a single line using brackets. However, keeping the variable creates a repeatable reference for the object. The next step is to execute the method. 3. In the PowerShell console, type the following: $bits.stopservice()

__GENUS __CLASS __SUPERCLASS __DYNASTY __RELPATH __PROPERTY_COUNT __DERIVATION __SERVER __NAMESPACE __PATH ReturnValue

: : : : : : : : : : :

2 __PARAMETERS __PARAMETERS 1 {}

0

You will notice that after executing the method, you will get return information from WMI. The most important of this information is the return code. The return code is also method and class specific so these need to be referenced. However, as a general rule, a return code of zero is a success and any other return code is an error of some description. For the StopService method, all the following are possible return codes. Return Code

Description

Return Code

Description

0

Success

13

Service dependency failure

1

Not supported

14

Service disabled

2

Access denied

15

Service logon failed

3

Dependent services running

16

Service marked for deletion

4

Invalid service control

17

Service no thread

5

Service cannot accept control

18

Status circular dependency

6

Service not active

19

Status duplicate name

7

Service request timeout

20

Status - invalid name

8

Unknown failure

21

Status - invalid parameter

9

Path not found

22

Status - invalid service account

10

Service already stopped

23

Status - service exists

11

Service database locked

24

Service already paused

12

Service dependency deleted

As you can see, the return codes can contain a lot of useful status information.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 284 of 361

Now, in this circumstance, you have changed the status of the bits service from running to stopped. Check out the results In the PowerShell console, type the following: $bits ExitCode Name ProcessId StartMode State Status

: : : : : :

0 BITS 1052 Auto Running OK

Clearly, the output appears incorrect? The output using the variable reference shows that the service is still running − and this is after you have executed the stopservice method and got a return code of 0 for success. The issue here is that the data in the $bit variable is not dynamic. Therefore, because WMI is a query-based system the information stored in the $bit reference is the status at the time of assignment to the variable. If you want to look at the current status, you need to run the query and assignment again. 4. Type the following in the PowerShell console to execute the query and assignment again. $bits = get-wmiobject –namespace “root\cimv2” –class win32_service –filter “name=’bits’”

5. Now type the following to display the current status. $bits ExitCode Name ProcessId StartMode State Status

: : : : : :

0 BITS 1052 Auto Stopped OK

The stopservice method does not require any parameters to be passed when using the method call. However, there are other methods that require parameters to be passed. Now, look at another common method that you might use when managing services with WMI. This is the changestartmode method. This method allows you to change the start mode of the server. There are several types of start modes that can be set. By specifying this, the startmode will be changed accordingly. To use the parameter in PowerShell, like all other methods, use a string with the value from the table. An advantage of this WMI class is that the return codes for this method are the same as the return codes for the stopservice method. Below are the parameters for the changestartmode method: Value

Meaning

Boot

Device driver started by the operating system loader. This value is valid only for driver services

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 285 of 361

System

Device driver started by the operating system initialization process. This value is valid only for driver services

Automatic

Service to be started automatically by the service control manager during system startup

Manual

Service to be started by the service control manager when a process calls the StartService method

Disabled

Service that can no longer be started.

Now, change the start mode of the bits service from Auto to manual. 6. In the PowerShell console type the following: $bits.changestartmode(“manual”) __GENUS __CLASS __SUPERCLASS __DYNASTY __RELPATH __PROPERTY_COUNT __DERIVATION __SERVER __NAMESPACE __PATH ReturnValue

: : : : : : : : : : :

2 __PARAMETERS __PARAMETERS 1 {}

0

To get the current status of the service after the change you can either re-execute the query, or execute a new one. 7. In the PowerShell console, type the following to check the current status. Get-wmiobject –namespace “root\cimv2” –class “win32_service” –filter “name=’bits’”

ExitCode Name ProcessId StartMode State Status

Microsoft | Services

: : : : : :

0 BITS 1052 Manual Stopped OK

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 286 of 361

Exercise 4: Common WMI Classes Used One challenge with WMI is finding where the information you need is stored. This is partly due to the size of the WMI class library. There are more than 900 classes on a typical machine, each containing multiple properties. This makes it very easy to become overwhelmed unless you know of some of the key common classes that contain most of the information you may need (as a system administrator). Once you are familiar with WMI, you might find that of the over 900 classes there are only a dozen or so that you use regularly. This section describes some of the common classes and their contents, and demonstrates using some of them. Some of these you have already looked at in this lesson and some of these will be new. Class name

Description

Win32_bios

Contains information from the computer bios. Information such as machine model and serial number can be obtained

win32_computersystem

Contains some hardware and operating system information about a system. This is good general class for system information

win32_diskdrive

Contains information about physical drives on a system as presented to windows.

win32_logicaldisk

Contains information about logical drives on a system as presented to windows. This class can also be used to schedule or cancel a scheduled chkdsk scan at boot.

Win32_NetworkAdapterConfiguration

Contains information about the network adapters on the system. This class can also be used to set network configurations such as IP addresses and DNS servers.

win32_operatingsystem

Contains detailed information about the current operating system

win32_pingstatus

This class performs a WMI ping on a remote target.

win32_printer

Contains information about printers on the local system

Win32_PrinterDriver

Contains information about the current printer drivers installed on a system

Win32_Printershare

Contains information about any shared printers on a system

Win32_PrinterConfiguration

Contains information about printer configuration on a system

win32_printjob

Contains information about print jobs on a system

win32_process

Contains information about processes on a system. It can also be used to start and stop processes

win32_processor

Contains information about the CPU of a system

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 287 of 361

win32_product

Contains information about software that has been installed via the Windows Installer service. Note that this class is not supported on Windows Server 2003, Windows XP or Windows 2000.

Win32_QuickFixEngineering

Contains information about the current applied hotfixes for a system

win32_service

Contains information about the services on a system. can also be used to change the state and configuration of the services

win32_share

Contains information about the current network shares on a system. can also be used to create network shares on a system

win32_systemenclosure

Contains information about a physical system enclosure. This is mostly useful for server system.

win32_timezone

Contains time zone information for a system. This includes the time zone offset from UTC and if daylight saving is in effect.

win32_userprofile

Contains information about the user profiles on a system

win32_utctime

Contains information about the current time, broken down into hours, minutes, seconds, day, month and year.

As you can see from the classes in the table, a large amount of system information is covered by these classes. While these will not exclusively be the WMI classes you will use, they will contain most of the information that you need as a systems administrator. Now you will look as some of the classes that have not been dealt with already.

Task 1: Understand Win32_pingstatus The win32_Pingstatus class is a special WMI class. This class is used to perform a WMI ping on a target by way of a WMI query. This is very useful in scripts for two main reasons. It a very quick to perform a WMI ping when the target responds. This makes writing scripts that ping multiple machines run quite fast when the majority of targets respond. The second use of this is to test whether or not a WMI connection can be established before running a WMI query on a remote machine. This is a good practice when using WMI on a remote target. This allows you to test the target first with a WMI ping and, if it succeeds, proceed to the WMI query, or handle errors if not. The means that it is a great candidate to build into a function library and dot source in most scripts. The class works by using a WQL query of the class and specifying the target in the where section of the query. This can be the NetBIOS name, FQDN or IP address of the machine to ping. For example, Get-wmiobject –query ‘select * from win32_pingstatus where address="syddc01"’

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 288 of 361

Below is an example of building the WMI ping into a function. The examples also include a function to look up the result code from the query and display the description for the return code. 8. Open the ISE and enter the following code: #functions Function wmiping($strcomputername) { $strQuery = "select * from win32_pingstatus where address = '" + $strcomputername + "'" $wmi = Get-WmiObject -Query $strQuery Write-Host "Pinging $strcomputername ... " if ($($wmi.statuscode) -eq $null) { $rtnvalue = $($wmi.PrimaryAddressResolutionStatus) } else {$rtnvalue = $($wmi.statuscode)} return $rtnvalue } Function pingerror($errcode) { switch ($errcode) { 11001 {$errdetails 11002 {$errdetails 11003 {$errdetails 11004 {$errdetails 11005 {$errdetails 11006 {$errdetails 11007 {$errdetails 11008 {$errdetails 11009 {$errdetails 11010 {$errdetails 11011 {$errdetails 11012 {$errdetails 11013 {$errdetails 11014 {$errdetails 11015 {$errdetails 11016 {$errdetails 11017 {$errdetails 11018 {$errdetails 11032 {$errdetails 11050 {$errdetails

= = = = = = = = = = = = = = = = = = = =

"Buffer Too Small"} "Destination Net Unreachable"} "Destination Host Unreachable"} "Destination Protocol Unreachable"} "Destination Port Unreachable"} "No Resources"} "Bad Option"} "Hardware Error"} "Packet Too Big"} "Request Timed Out"} "Bad Request"} "Bad Route"} "TimeToLive Expired Transit"} "TimeToLive Expired Reassembly"} "Parameter Problem"} "Source Quench"} "Option Too Big"} "Bad Destination"} "Negotiating IPSEC"} "General Failure"}

default {$errdetails = "unknown error"} } return $errdetails } # Main code cls do { Write-Host "This script will ping an IP address or machine name"

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 289 of 361

$strcomp = Read-Host "Please enter an IP address or computer name to ping" $rtn = wmiping $strcomp if ($rtn -eq 0) {"success"} else { $rtn = pingerror $rtn "error : " + $rtn} } until ($invalue -eq "q")

9. Save the file as WMIPingScript.ps1. 10. Run the script and enter a machine or IP address to ping when prompted.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 290 of 361

Lesson 9 Hands-On : Windows Management Instrumentation (WMI) Introduction In this section, you will cover the core concepts of Windows Management Instrumentation, better known as ‘WMI’. These concepts include working with classes, gathering data both locally and remotely as well as real-world applications.

Objectives After completing this lab, you will be able to: 

Describe the core WMI concepts in Windows



Leverage the Get-WMIObject cmdlet to access WMI from within PowerShell



Review some of the most commonly used WMI classes



Discover gathering data remotely using Get-WMIObject



Filter and sort returned WMI data



Provide best practices when leveraging WMI in scripting

Prerequisites 

A Windows 7 workstation logged in with administrator credentials



A Windows 2008 server logged in with administrator credentials

Estimated time to complete this lab 60 minutes

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 291 of 361

Exercise 1: WMI Classes and Queries Objectives In this exercise, you will: 

Use the most common WMI cmdlet in Powershell: get-wmiobject



Enumerate some basic information with it



Try different syntaxes for querying



Discover some useful, frequently used classes



Generate some errors to see how they appear

Estimated time to complete this lab 10 minutes

Scenario Now that you have seen how to access WMI in Windows, you can use PowerShell 1.0 or 2.0 to get information from it. At this time, your focus will be on getting only local information.

Task 1: Log on to the VM environment Log on to Windows 7 Enterprise client: 

Username: Contoso\Administrator



Password: P@ssword

Task 2: Open Windows PowerShell Session Click the

icon on the windows task bar

The PowerShell window will open.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 292 of 361

Task 3: Examine a WMI Class 1. In the PowerShell console, run the following command:: get-wmiobject

-Class “Win32_quickfixengineering”

This is the basic Cmdlet to enumerate the contents of a WMI Class. You provide only the Class Name; all the other parameters have good defaults. This WMI class, win32_quickfixengineering, will display the current applied hotfixes on a system. 2. In the PowerShell console, run the following to reformat the data. Get-wmiobject –class “win32_quickfixengineering” | format-table hotfixid, description, installedby, installedon

You will now see that the source column is no longer displayed and the KB number is now the first column displayed. 3. Type the following into the PowerShell console to export the list of hotfixes to a text file. Get-wmiobject –class “win32_quickfixengineering” | select-object hotfixid, description, installedby, installedon > hotfixes.txt

Now examine the text file produced. You will see that it contains the list of the hotfixes. Question A:

notepad .\hotfixes.txtWhy was select-object used instead of formattable in the example above?

Answer: Select object was used as it discards any additional data aside from the specified properties. Format-table on the other hand is for formatting the information displayed in the PowerShell console. 4. Type the following in the PowerShell console to export the list of hotfixes to a .CSV file. Get-wmiobject –class “win32_quickfixengineering” | export-csv hotfixes.csv ` -notypeinformation

Now examine the .CSV file in notepad. notepad .\hotfixes.csv

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 293 of 361

Exercise 2: Basic Filtering Objectives In this exercise, you will: 

Work with the network adapter configuration WMI class



Filter the class to find the active network adapter

Estimated time to complete this lab 10 minutes

Scenario One very useful WMI class is the win32_networkadapterconfiguration class. This class however needs to be filtered to get the useful information out. This is common with many WMI classes.

Task 1: Log on to the VM environment Log on to Windows 7 Enterprise client: 

User name; Contoso\Administrator



Password:P@ssword

Task 2: Open Windows PowerShell Session Click the

icon on the windows task bar

The PowerShell window will open.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 294 of 361

Task 3: List network adapters on the system 1. In the PowerShell console, type the following command to list the network adapters on the local system: Get-wmiobject –namespace “root\cimv2” –class win32_networkadapterconfiguration

You will now see a long list of network adapters available on the system. Some of these include the RAS adapters, the WAN mini port and other such adapters. For most purposes, you are not concerned or interested in these adapters. However if you were there is lots of information available for these. Most of the time you will be interested in the adapter that contains a valid IP address as this will be the active NIC that is being used. To look at this adapter, you need to filter out the other adapters. Question B:

Based on the information displayed, what is the property that offers the easiest way to filter network adapters?

Answer : From what is displayed, the IP address will be the easiest way to filter the network adapters. 2. In the PowerShell console, type the following command to filter the network adapters: Get-wmiobject –namespace “root\cimv2” –class win32_networkadapterconfiguration | where-object {$_.ipaddress –ne $null}

This will filter the network adapters down to just the NICs that have an IP address. However, you are aware that using where-object is not the most effective way of filtering WMI instances. The IPAddress property is a little tricky. This property is an array property, since a NIC can have multiple IP Addresses, although this is not very common. Therefore, querying this property for a NULL value will not work. Instead, look at all the properties available for the network adapter. 3. In the PowerShell console, type the following to display all the information for the network adapter with an IP address. Get-wmiobject –namespace “root\cimv2” –class win32_networkadapterconfiguration | where-object {$_.ipaddress –ne $null} | format-list *

You will see all the properties for the network adapter displayed. Examine this information and look at the properties. One of these properties will let you know if the network adapter has an IP address. Question C:

What is the property that lets you know if the network adapter has an IP Address?

Answer: The property is IPEnabled. Now that you have found the property IPEnabled, you can use it in a WMI query or filter to get just the NIC or NICs with IP Addresses.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 295 of 361

4. In the PowerShell console, run the following command to filter using a WMI query. Get-wmiobject –query “select * from win32_networkadapterconfiguration where ipenabled = ‘true’ “

The NIC with an IP address configured will now be displayed. 5. Now type the following to display the same information using the -filter parameter. Get-wmiobject –namespace “root\cimv2” –class win32_networkadapterconfiguration ` –filter “ipenabled = ‘true’ ”

You will see the information displayed is the same using either method. It is a matter of preference as to which you will use. 6. In the PowerShell console, run the following command to display all the information for the WMI class instance. Get-wmiobject –namespace “root\cimv2” –class win32_networkadapterconfiguration ` –filter “ipenabled = ‘true’ ” | format-list [a-z]*

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 296 of 361

Exercise 3: WMI Method Execution Objectives In this exercise, you will: 

Get information from remote machines, using WMI



Use the WMI ping to test connectivity



Execute WMI methods to make configuration changes

Estimated time to complete this lab 15 minutes

Scenario When working with WMI classes and information it is possible to not only obtain information, but also to make changes using WMI methods. In this exercise you will execute some methods on the win32_networkadapterconfiguration class.

Task 1: Log on to the VM environment Log on to Windows 7 Enterprise client. 

Username: Contoso\Administrator



Password: P@ssword

Task 2: Open Windows PowerShell Session Click the

icon on the windows task bar

The PowerShell window will open.

Task 3: Test DNS and Gateway Values Following on from the previous example of looking at the network adapters that have an IP address, the next step is to verify the DNS settings and gateway to be valid. To do this, you will first get the values, and then use WMI ping to test the values. There is a much easier way to test the network addresses through WMI, which is testconnection. However, as this is a WMI lesson you will use WMI instead. 1. In the PowerShell console, run the following command to list the network adapters on the local system that have a valid IP address: Get-wmiobject –query “select * from win32_networkadapterconfiguration where ipenabled = ‘true’“ | format-list *

The DNS servers and gateway properties will now be in the list of properties. You will now use WMI ping to verify that these values are correct. 2. Run the following command to test the first DNS server:

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 297 of 361

Get-wmiobject –query “select * from win32_pingstatus where address=’’” | ft ipv4address, statuscode -autosize

Where is the IP address of the DNS server from the first query in the DNSServerSearchOrder property. Question A:

Did the query return a success or a failure?

Answer: The first DNS server will ping successfully. 3. Repeat the command from step 2 but replace it with a second DNS server. Get-wmiobject –query “select * from win32_pingstatus where address=’’” | ft ipv4address, statuscode -autosize

Where is the IP address of another DNS server from the first query in the DNSServerSearchOrder property. Question B:

Question? Did the query return a success or a failure?

Answer: The second DNS server will not ping successfully, as it is not online in the lab environment. Now you will test the gateway to verify that it is correct. 4. Type the following command to verify the default gateway address. Get-wmiobject –query “select * from win32_pingstatus where address=’’” | ft ipv4address, statuscode -autosize

Where is the IP address of the default gateway from the first query. Question C:

Question? Did the query return a success or a failure?

Answer: The default gateway server will ping successfully. Now that the DNS servers and default gateway addresses have been verified, you can now use WMI methods to modify these values.

Task 4: Set DNS Server Search Order To set the DNS server search order, the win32_networkadapterconfiguration class includes a method called setDNSServerSearchOrder which allows you to both define the DNS servers and also to set the search order. To use this method, you will need to isolate the instances of the network adapter class that contains the adapter with the valid IP address. 1. Run the following query from Exercise 2 to get the active network adapter. This will be assigned to a variable for easy reference. $mynic = Get-wmiobject –query “select * from win32_networkadapterconfiguration where ipenabled = ‘true’ “

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 298 of 361

Now that the active network is assigned to the variable, you can easily execute the method. However, just before you do that, verify that the variable contains the network adapter of interest. 2. Run the following command to list the active network adapter: $mynic

Note: If you do not see the active network adapter listed, then there is something wrong with the query.

Now you are ready to set the DNS servers and the search order. The setDNSServerSearchOrder method will accept an array of strings for the DNS servers. If you are setting a single DNS server (which is not best practice) then you can use a string for the single DNS server − PowerShell will convert this to an array for the method execution. However if you are going to set multiple DNS servers and the search order, then you need to supply an array of strings. The easiest way to do this is to create a variable with the array of strings and then use this variable in the method call. 3. Run the following command to set the single DNS server value: $mynic.SetDNSServerSearchOrder(“192.168.0.1”)

The return code should be zero indicating that the value has been changed. To verify the result, you need to run the query again, as $mynic will reflect the configuration as the time of assignment. Get-wmiobject –query “select * from win32_networkadapterconfiguration where ipenabled = ‘true’ “ | format-list *

You will now see that the DNS servers have changed and will only be a single address. If this is not the case, then look at the method call and result code to determine what has gone wrong. Now you will use a similar method to clear the current gateway value.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 299 of 361

Task 5: Set and Clear the Default Gateway Value Using the setgateways method, you can also set the default gateway (and other gateways if required). This method can also be used to clear the value. However, this is not obvious at first. Similar to the setDNSSearchOrder method, this method can pass an array of address for multiple gateways, or a single address for a single gateway. There is also an optional parameter, the gatewaycost, which again is either a single value or an array of values for multiple gateways. To clear the gateway value, you need to supply the IP address of the local machine as the gateway. If you supply a blank or null value to the method call, neither of these will work. There is also no method to clear or delete the value. 1. Run the following command to clear the gateway value: $mynic.setgateways(“”)

Where is the IP address of the local machine. 2. Run the following command to verify the gateway has been changed: Get-wmiobject -query "select * from win32_networkadapterconfiguration where ipenabled = 'true'"

The default gateway should now be blank in the adapter properties or 0.0.0.0 under PowerShell. Now you need to set the value of this back to the previous value. 3. Run the following command to set the gateway value: $mynic.setgateways(“192.168.0.1”)

4. Run the following command to verify the gateway has been changed: Get-wmiobject -query "select * from win32_networkadapterconfiguration where ipenabled = 'true'"

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 300 of 361

PowerShell for the IT Administrator, Part 1 Lesson 10: Registry, Event Log and ACL Management

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Lesson 10 Demonstration : Registry, Event Log and ACL Management Introduction In the previous modules, you have learned about Windows Powershell fundamentals along with WMI and Active Directory management. The other important Windows constituents that administrators commonly manage are system Registry, Event Logs and Access control lists (ACL) on the registry or file system. Windows Powershell offers a cluster of cmdlets to manage Event Logs and ACLs. The Registry provider lets you get, add, change, clear, and delete registry keys and values in Windows PowerShell. In addition, most of these integral components of Windows can also be managed using Windows Powershell through select .Net and WMI classes.

Objectives After completing this lab, you will be able to: 

Manage the registry using the registry provider.



Access Remote registry using Windows Powershell.



Manage Event Logs and file system ACLs using Windows Powershell cmdlets.

Prerequisites Windows 2008 server and Windows 7 workstation logged on to with domain administrator credentials.

Estimated time to complete this lesson 60 minutes

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 302 of 361

Exercise 1: Using the Registry Provider Objectives In this exercise, you will: 

Understand the usage of the registry provider.



Learn about the techniques to read, query, create, modify and delete registry keys/values using the Windows Powershell registry provider.

Scenario The Windows Powershell registry provider simplifies access to the registry by exposing the hives as drives. The registry provider provides access to the local registry keys and values. The registry provider can be used to access a remote machine’s registry if used within a PS v2.0 Remote session. The Registry Provider allows us to access two PS Drives: 

HKCU (HKEY_CURRENT_USER)



HKLM (HKEY_LOCAL_MACHINE)

The following command lists the PS Drives offered by the registry provider. PS C:\> get-PSProvider registry Name ---Registry

Capabilities -----------ShouldProcess, Transactions

Drives -----{HKLM, HKCU}

Additional registry PS drives can be created for a specific registry key: New-PSDrive Run Registry "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" PS C:\> cd run: PS Run:\>

In order to manage the registry items exposed by the provider, the following cmdlets are designed to work with the data. Name

Synopsis

Clear-ItemProperty

Deletes the value of a property but does not delete the property

Copy-ItemProperty

Copies a property and value from a specified location to another location

Get-ChildItem

Gets the items and child items in one or more specified locations

Get-ItemProperty

Gets the properties of a specified item

Move-ItemProperty

Moves a property from one location to another

Get-Item

Gets the item at the specified location

New-Item

Creates a new item

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 303 of 361

Set-Item

Changes the value of an item to the value specified in the command

Remove-Item

Deletes the specified items

Move-Item

Moves an item from one location to another

Rename-Item

Renames an item in a Windows PowerShell provider namespace

Copy-Item

Copies an item from one location to another within a namespace

Clear-Item

Deletes the contents of an item, but does not delete the item

New-ItemProperty

Creates a new property for an item and sets its value

Remove-ItemProperty

Deletes the property and its value from an item

Rename-ItemProperty

Renames a property of an item

Set-ItemProperty

Creates or changes the value of a property of an item

For example, in the drives that are supported by the Registry provider, you can use New-Item to create a new registry key. In the following sections of this exercise, we will demonstrate the following operations using the registry provider: 

Navigating the registry



Testing key existence



Reading registry properties



Creating registry keys



Creating registry properties



Modifying registry properties

Task 1: Log on to the VM environment 1. Log on to the Windows 7 client as Contoso\Administrator

Task 2: Navigating the registry using Windows Powershell Registry Provider 1. On the Windows task bar, locate and click the

icon.

This will open the Windows Powershell menu. 2. At the PS prompt, enter the following command to connect to the HKCU (HKEY_CURRENT_USER) PSDrive. PS C:\> cd hkcu: PS HKCU:\>

3. List the sub keys in the HKCU hive using Dir or GCI. PS HKCU:\> dir Hive: HKEY_CURRENT_USER

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 304 of 361

SKC --2 2 ..

0 37 ..

VC Name ----AppEvents Console

4. You can set the location (cd/sl) to any registry key as follows: PS HKCU:\> cd software\microsoft\windows\currentversion\explorer PS HKCU:\software\microsoft\windows\currentversion\explorer>

5. Similarly, you can directly set the location to a key in any of the registry providers (HKLM: in the below command) from any other PS Drive. PS HKCU:\> cd HKLM:\software\microsoft PS HKLM:\software\microsoft>

Task 3: Testing registry key existence using the Registry Provider In order to search for a registry key, you can use the cmdlets Get-ChildItem or Get-Item 1. Enter the below command (using GCI) with the full path to the registry location that you want to check for existence. PS HKLM:\> GCI hklm:\software\microsoft\windows Hive: HKEY_LOCAL_MACHINE\software\microsoft\windows SKC VC --- -82 9 0 1 .. ..

Name ---CurrentVersion DWM

Property -------{SM_GamesName, SM_ConfigureProgramsName, {UseDpiScaling}

Unlike Get-ChildItem, using get-item does not enumerate the sub keys, but only returns the target Registry key. PS HKLM:\> Get-Item hklm:\software\microsoft\windows Hive: HKEY_LOCAL_MACHINE\software\microsoft

SKC --12

VC Name -- ---0 windows

Property -------{}

2. To recursively search a registry key, the parameters –recurse and –include can be used as follows: PS HKLM:\> Get-childitem HKLM:\software -recurse -include Windows

This will find all the keys that contain the word "Windows" in the key names. 3. The Registry item returned, correspond to Microsoft.Win32.RegistryKey object that provides the following associated member types. PS HKLM:\> Get-item hklm:\software\microsoft\windows | Get-Member

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 305 of 361

TypeName: Microsoft.Win32.RegistryKey Name ---Close CreateObjRef CreateSubKey DeleteSubKey DeleteSubKeyTree DeleteValue Equals Flush GetAccessControl GetHashCode GetLifetimeService GetSubKeyNames GetType GetValue GetValueKind GetValueNames InitializeLifetimeService OpenSubKey SetAccessControl SetValue ToString Property PSChildName PSDrive PSIsContainer PSParentPath PSPath PSProvider Name SubKeyCount ValueCount

MemberType ---------Method Method Method Method Method Method Method Method Method Method Method Method Method Method Method Method Method Method Method Method Method NoteProperty NoteProperty NoteProperty NoteProperty NoteProperty NoteProperty NoteProperty Property Property Property

Definition ---------System.Void Close() System.Runtime.Remoting.ObjRef Crea.. Microsoft.Win32.RegistryKey CreateS.. System.Void DeleteSubKey(string sub.. System.Void DeleteSubKeyTree(string.. System.Void DeleteValue(string name.. bool Equals(System.Object obj) System.Void Flush() System.Security.AccessControl.Regis.. int GetHashCode() System.Object GetLifetimeService() string[] GetSubKeyNames() type GetType() System.Object GetValue(string name) Microsoft.Win32.RegistryValueKind G.. string[] GetValueNames() System.Object InitializeLifetimeSer.. Microsoft.Win32.RegistryKey OpenSub.. System.Void SetAccessControl(System.. System.Void SetValue(string name, S.. string ToString() System.String[] Property=System.Str.. System.String PSChildName=CurrentVe.. System.Management.Automation.PSDriv.. System.Boolean PSIsContainer=True System.String PSParentPath=Microsof.. System.String PSPath=Microsoft.Powe.. System.Management.Automation.Provid.. System.String Name {get;} System.Int32 SubKeyCount {get;} System.Int32 ValueCount {get;}

4. To enumerate a list of subkeys, enter the following command. PS HKLM:\> (Get-item hklm:\software\microsoft\windows).getsubkeynames() CurrentVersion DWM Help HTML Help ITStorage ScheduledDiagnostics ScriptedDiagnosticsProvider Tablet PC TabletPC Windows Error Reporting Windows Search WindowsUp

5. To check if a Registry sub Key exists, you can also use the containment operator contains. PS HKLM:\> (Get-item hklm:\software\microsoft\windows).getsubkeynames() -contains "windows search"

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 306 of 361

True PS HKLM:\>

In the above example, the output returns TRUE because the sub key named “Windows Search” exists in the target parent key.

Task 4: Reading the Registry Properties 1. To enumerate the registry values inside a key, use the cmdlet Get-Itemproperty as shown in the command that follows: PS HKLM:\> Get-ItemProperty HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1 PSPath:Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\P owerShell\1 PSParentPath:Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Micro soft\PowerShell PSChildName: 1 PSDrive: HKLM PSProvider: Microsoft.PowerShell.Core\Registry Install: 1 PID: 89383-100-0001260-04309 PS HKLM:\>

In the above output, you will notice that along with the registry values in the key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1, few of the Powershell properties are also returned. 2. If you would like to determine the data contained in a particular value, use the value name (as a) property in the output shown in the previous step. In the following example, the data in the value named PID is obtained. PS HKLM:\> $Regvalues= GP HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1 PS HKLM:\>$regvalues.pid 89383-100-0001260-04309 PS HKLM:\>

3. As shown below, you can also return the value data using the getvalue method on the key. PS HKLM:\> (Get-Item HKLM:\SOFTWARE\Microsoft\PowerShell\1).getvalue("pid") 89383-100-0001260-04309 PS HKLM:\>

Task 5: Creating Registry Keys 1. The Cmdlet New-Item can be used to create a registry key. Enter the below command containing the full path of the registry key that you want to create. PS HKLM:\> new-item hkcu:\software\MyApplication Hive: HKEY_CURRENT_USER\software

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 307 of 361

SKC --0

VC Name -- ---0 MyApplication

Property -------{}

PS HKLM:\>

2. The following syntax using the parameters –path and –name will create a registry key named “OurApplication". PS HKLM:\> new-item -Path hkcu:\software -Name OurApplication Hive: HKEY_CURRENT_USER\software

SKC --0

VC Name -- ---0 OurApplication

Property -------{}

PS HKLM:\>

3. Alternatively, you can also run the following commands from the local path to create a registry key. PS HKCU:\software> New-Item yourApplication Hive: HKEY_CURRENT_USER\software SKC --0

VC Name -- ---0 yourApplication

Property -------{}

PS HKCU:\software>

Or, PS HKCU:\software> New-Item

-Path . -Name hisApplication

Hive: HKEY_CURRENT_USER\software SKC --0

VC Name -- ---0 hisApplication

Property -------{}

PS HKCU:\software>

Note: Use the cmdlet Remove-Item to delete registry keys. For more information on how to use Remove-Item, obtain help on the cmdlet (help remove-item –full)

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 308 of 361

Task 6: Creating Registry Properties 1. To create registry values of different data types (REG_SZ, REG_MULTI_SZ, REG_DWORD, REG_EXPAND_SZ, REG_QWORD, REG_BINARY), use the cmdlet New-Itemproperty. Note: This cmdlet does not add properties to an object. To add a property to an instance of an object, use the Add-Member cmdlet. To add a property to all objects of a particular type, edit the Types.ps1xml file.

2. Enter the command below to create a DWORD property named ‘Config1’ with a value of ‘1024’ in the registry key ‘MyApplication’. PS HKLM:\> New-ItemProperty HKCU:\Software\MyApplication -name "Config1" -value "1024" -propertyType DWORD PSPath : Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER\Software\MyApplication PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER\Software PSChildName : MyApplication PSDrive : HKCU PSProvider : Microsoft.PowerShell.Core\Registry Config1 : 1024 PS HKLM:\>

The code above assumes that the registry key ‘MyApplication’ exists prior to running the command. If the parameter -propertyType is not used, the registry value created will be of the data type REG_SZ. Note: Use the cmdlet Remove-ItemProperty to delete registry values. For more information on how to use Remove-ItemProperty, obtain help on the cmdlet (help remove-itemproperty –full)

Task 7: Modifying Registry Properties 1. The cmdlet Set-ItemProperty can be used on a specified registry item to create or change the value of a property. The example shown below modifies the value of an existing DWORD property created in the previous exercise to ‘2048’. PS HKLM:\> Set-ItemProperty –path HKCU:\Software\MyApplication -name "Config1" value "2048" PS HKLM:\>

If the DWORD property did not pre-exist, a new REG_SZ property with the value of “2048” would have been created. Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 309 of 361

2. The parameter–force used with New-ItemProperty can also set/overwrite the value of an existing registry property retaining its data type. For example: PS HKLM:\> New-ItemProperty –path HKCU:\Software\MyApplication -name "Config1" value "4096" -force PSPath : Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER\Software\MyApplication PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER\Software PSChildName : MyApplication PSDrive : HKCU PSProvider : Microsoft.PowerShell.Core\Registry Config1 : 4096 PS HKLM:\>

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 310 of 361

Exercise 2: Remote Registry Management Objectives In this exercise, you will: 

Understand the techniques of accessing remote registry using Powershell.



Learn how to read, query, create, modify and delete remote registry keys/values using the .Net Framework RegistryKey class.

Scenario In the previous exercise, we have learned how to access the local registry using the Windows Powershell registry provider. Though PowerShell 2.0 Remoting is the easiest way to deal with remote registry access, it will only work in environments with PowerShell v2.0 installed and Windows Remote Management (WINRM) allowed on the remote machines. In this exercise, we will explore remote registry management using the Microsoft .Net Framework Microsoft.Win32.Registry class.

Task 1: Connect to remote registry hive 1. To use the Microsoft.Win32.Registry class in PowerShell, access the OpenRemoteBaseKey static method to connect to the required registry hive of a remote computer. The example below connects to the HKLM registry hive (LocalMachine) of the server named “syddc01”. $RemoteReg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey(“LocalMachine”, “Syddc01”)

The commonly used registry hive names are as: 

ClassesRoot – HKEY_CLASSES_ROOT



CurrentUser – HKEY_CURRENT_USER



LocalMachine – HKEY_LOCAL_MACHINE



Users – HKEY_USERS



PerformanceData – HKEY_PERFORMANCE_DATA



CurrentConfig – HKEY_CURRENT_CONFIG



DynData – HKEY_DYN_DATA

2. The corresponding Microsoft.Win32.RegistryKey object (as created above) provides the following associated member types to read, create, delete and change the registry key and properties.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 311 of 361

PS C:\> $RemoteReg | Get-Member TypeName: Microsoft.Win32.RegistryKey Name ---Close CreateObjRef CreateSubKey DeleteSubKey DeleteSubKeyTree DeleteValue Equals Flush GetAccessControl GetHashCode GetLifetimeService GetSubKeyNames GetType GetValue GetValueKind GetValueNames InitializeLifetimeService OpenSubKey SetAccessControl SetValue ToString Property PSChildName PSDrive PSIsContainer PSParentPath PSPath PSProvider Name SubKeyCount ValueCount

MemberType ---------Method Method Method Method Method Method Method Method Method Method Method Method Method Method Method Method Method Method Method Method Method NoteProperty NoteProperty NoteProperty NoteProperty NoteProperty NoteProperty NoteProperty Property Property Property

Definition ---------System.Void Close() System.Runtime.Remoting.ObjRef Crea.. Microsoft.Win32.RegistryKey CreateS.. System.Void DeleteSubKey(string sub.. System.Void DeleteSubKeyTree(string.. System.Void DeleteValue(string name.. bool Equals(System.Object obj) System.Void Flush() System.Security.AccessControl.Regis.. int GetHashCode() System.Object GetLifetimeService() string[] GetSubKeyNames() type GetType() System.Object GetValue(string name) Microsoft.Win32.RegistryValueKind G.. string[] GetValueNames() System.Object InitializeLifetimeSer.. Microsoft.Win32.RegistryKey OpenSub.. System.Void SetAccessControl(System.. System.Void SetValue(string name, S.. string ToString() System.String[] Property=System.Str.. System.String PSChildName=CurrentVe.. System.Management.Automation.PSDriv.. System.Boolean PSIsContainer=True System.String PSParentPath=Microsof.. System.String PSPath=Microsoft.Powe.. System.Management.Automation.Provid.. System.String Name {get;} System.Int32 SubKeyCount {get;} System.Int32 ValueCount {get;}

The following sections of this exercise will cover the usage of the commonly used methods and demonstrate the following remote registry operations: 

Navigating the registry



Testing key existence



Reading registry properties



Creating registry keys



Creating registry properties



Modifying registry properties

Task 2: Log on to the VM environment 1. Log on to the Windows 7 client as Contoso\Administrator

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 312 of 361

Task 3: Navigating the remote registry 1. On the windows task bar locate and click the

icon.

This will open the Windows Powershell menu. 2. At the PS prompt, enter the following command to create the Microsoft.Win32.Registry class object. PS C:\> $RemoteReg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey(“LocalMachine”, “Syddc01”)

The above variable stores information about the HKLM registry hive of the remote computer “Syddc01”. 3. You can connect to any accessible sub key using the opensubkey() method PS C:\> $dotnetreg = $RemoteReg.OpenSubKey("Software\Microsoft\NET Framework Setup\NDP\v2.0.50727") PS C:\> $dotnetreg SKC --23

VC Name -- ---6

Property --------

The opensubkey() method requires the subkey path parameter as a shown above.

Task 4: Testing remote registry key existence 1. In order to list the sub keys in a registry location use the getsubkeynames() method as shown below PS C:\> $RemoteReg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey(“LocalMachine”, “Syddc01”) PS C:\> $RemoteReg.GetSubKeyNames() BCD00000000 HARDWARE SAM SECURITY SOFTWARE SYSTEM PS C:\>

2. To determine the existence of a key, you can use the where-object filter on the list of returned subkey names. PS C:\> $psreg = $RemoteReg.OpenSubKey("SOFTWARE\Microsoft\PowerShell\1") PS C:\> $psreg.getsubkeynames() | where {$_ -eq "ShellIds"} ShellIds PS C:\>

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 313 of 361

Task 4: Reading Remote Registry Properties 1. To enumerate the registry properties inside a key, use the GetValueNames() method on the RegistryKey object. In continuation to the above four commands, reuse the $psreg variable as follows: PS C:\> $psreg.GetValueNames() Install PID PS C:\>

2. If you would like to determine the data value contained in a particular property, use the GetValue() method with the property name as a parameter to the method. In the following example, the data in the property named PID is obtained. PS C:\> $psreg.GetValue("pid") 89383-100-0001260-04309 PS C:\>

3. The following code lists all the registry value names and their associated data at a time using the Foreach-Object loop. PS C:\> $psreg.GetvalueNames() Install : 1 PID : 89383-100-0001260-04309 PS C:\>

| foreach-object { "$_ : $($psreg.getvalue($_))"}

Task 5: Creating Remote Registry keys 1. At the PS prompt, enter the following command to connect to the remote registry of the machine “Syddc01”. PS C:\> $RemoteReg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey(“LocalMachine”, “Syddc01”)

2. While using the OpenSubKey() method, provide the optional Boolean argument to open the subkey in R/W mode. However, it is always necessary to specify $true if you want to add, delete, or modify values or keys in a particular registry hive. In the following steps, a subkey will be created inside the target key “\Software\Microsoft”. PS C:\> $MSReg = $RemoteReg.OpenSubKey("Software\Microsoft”, $true) PS C:\>

3. Use the createsubkey() method to create a sub key in the target key “\Software\Microsoft”. PS C:\> $MSReg.CreateSubKey("MSData") SKC VC Name --- -- ---0 0 PS C:\>

Microsoft | Services

Property --------

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 314 of 361

Note: Use the methods deletesubkey() or deletesubkeytree() to delete registry keys on the RegistryKey class object.

Task 6: Creating Remote Registry properties 1. In the following example, you will create a DWORD property named “State” with the value of “1” in the registry key “MSdata” created in the previous step. Enter the following command to open the target sub key "Software\Microsoft\MSData” PS C:\> $MSDataReg = $RemoteReg.OpenSubKey("Software\Microsoft\MSData”, $true) PS C:\>

2. To create registry values of different data types use the method Setvalue() on the target RegistryKey object. PS C:\> $MSDataReg.setvalue("State", "1", "Dword") PS C:\>

If the data type argument (third place) to the setvalue() method is not passed, the registry value created will be of the type REG_SZ.

Task 7: Modifying Remote Registry properties The method setvalue() can also set/overwrite the value of an existing registry property retaining or changing its data type. 1. Run the following commands to change the value of the property “State” created in the previous step and hence verify the update. PS 1 PS PS 2 PS

C:\> $MSDataReg.getvalue("State") C:\> $MSDataReg.setvalue("State", "2", "Dword") C:\> $MSDataReg.getvalue("State") C:\>

Note: Use the method deletevalue() to delete a registry property on the RegistryKey class object.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 315 of 361

Exercise 3: Eventlog Cmdlets Objectives In this exercise, you will: 

Understand the techniques of managing local and remote Event Logs using Windows Powershell.



Learn about how to read, write, clear and search event logs.

Scenario Event Logs are special files that record significant events on your computer, such as, when a user logs on to the computer or when a program encounters an error. Starting with Windows Vista and Windows Server 2008 onwards, the operating system includes two categories of event logs:  

Windows Logs Applications and Services logs

Windows Logs (Classic Event Logs) The Windows Logs category includes the logs that were available on previous versions of Windows: the Application, Security, and System logs. It also includes two new logs: the Setup log and the ForwardedEvents log. Windows logs are intended to store events from legacy applications and events that apply to the entire system. Applications and Services Logs Applications and Services logs are a new category of event logs. These logs store events from a single application or component rather than events that might have system wide impact. Windows Powershell provides two cmdlets Get-EventLog and Get-WinEvent to manage the Classic and the newer event logs respectively. On a Windows 2003 or Windows XP machine, you can only use the legacy Get-EventLog cmdlet. On the other hand, Get-WinEvent can even read .etl, .evt, and .evtx log file formats

Task 1: Log onto the VM environment 1. Log on to the Windows 7 client as Contoso\Administrator

Task 2: The -EventLog cmdlets A number of Windows PowerShell cmdlets provide functionality to manage the Windows logs. The cmdlets that contain the EventLog noun (the EventLog cmdlets) work only on classic event logs.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 316 of 361

To get events from logs that use the Windows Event Log technology in Windows Vista and later versions of Windows, use Get-WinEvent, which is discussed in the next section of the exercise. 1. Enter the following command to list the cmdlets that contain the EventLog noun. PS C:\> gcm *-eventlog -CommandType cmdlet CommandType ----------Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet Cmdlet

Name ---Clear-EventLog Get-EventLog Limit-EventLog New-EventLog Remove-EventLog Show-EventLog Write-EventLog

Here is a synopsis of these cmdlets. Clear-EventLog Get-EventLog Limit-EventLog New-EventLog Remove-EventLog Show-Eventlog Write-EventLog

Deletes all entries from specified event logs on the local or remote computers Gets the events in a specified event log or a list of the event logs on a computer Sets the event log properties that limit the size of the event log and the age of its entries Creates a new event log and a new event source on a local or remote computer Deletes an event log or unregisters an event source Displays the event logs of the local or a remote computer in Event Viewer Writes an event to an event log

Note: All of the above cmdlets can be used with the –computer parameter to manage remote Windows event logs.

In the following examples, the common Event Log management scenarios will be covered. Read Windows Event Logs 1. On the windows task bar, locate and click the Powershell menu.

icon. This will open the Windows

2. At the PS prompt, enter the following command to list the Windows event logs on the machine. PS C:\>

Get-EventLog -list

Max(K) Retain OverflowAction ------ ------ --------------

Microsoft | Services

Entries Log ------- ---

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 317 of 361

15,168 20,480 512 20,480 8,192 102,400 15,168 15,360

0 0 7 0 0

OverwriteAsNeeded OverwriteAsNeeded OverwriteOlder OverwriteAsNeeded OverwriteAsNeeded 0 OverwriteAsNeeded 0 OverwriteAsNeeded 0 OverwriteAsNeeded

21,119 Application 0 HardwareEvents 0 Internet Explorer 0 Key Management Service 0 Media Center 128,242 Security 40,729 System 19,372 Windows PowerShell

3. The command below lists the last 5 ‘Netlogon’ errors reported in the System event log. PS C:\> get-eventlog -newest 5 -logname System -entrytype Error –Source Netlogon

Similarly, the other Windows event logs listed in Step (2) can be queried. Write an event to an Event Log If for instance, your script would like to write a log on the local or remote computer in the event of a failure or success of an operation, the cmdlet, Write-EventLog, can be useful. 4. Enter the following command to write an Application Event Log with Event ID 10005 and Source VSS. PS C:\> write-eventlog -logname Application -source VSS -eventID 10005 -entrytype Warning -message "Unable to copy the backup. For help contact your system administrator"

Clear event logs 5. The cmdlet, clear-cmdlet, deletes all entries from specified event logs on the local or remote computers. clear-eventlog -log application, system –confirm –computer syddc01

The above syntax will clear the Application and System event logs from the remote computer named ‘syddc01’.

Task 3: Get-WinEvent cmdlet As the format of event logs has changed considerably in Windows Vista and later operating systems, Powershell now includes a cmdlet, Get-WinEvent, directly targeted at enumerating these logs including remote computers. 1. You can continue to access the classic event logs by specifying their name as an argument to the –LogName parameter of the cmdlet as shown below: PS C:\> Get-WinEvent -LogName System –computer ‘syddc01’

2. The Get-Winevent cmdlet provides more information on the event log properties. PS C:\>

get-winevent -listlog System | format-list -property *

FileSize IsLogFull LastAccessTime LastWriteTime OldestRecordNumber RecordCount

Microsoft | Services

: : : : : :

16912384 False 6/24/2011 5:53:56 PM 10/5/2011 11:02:23 AM 147781 40761

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 318 of 361

LogName LogType LogIsolation IsEnabled IsClassicLog SecurityDescriptor

: : : : : :

System Administrative System True True O:BAG:SYD:(A;;0xf0007;;;SY)(A;;0x7;;;BA)(A;;0x ;;;SU)(A;;0x1;;;S-1-5-3)(A;;0x2;;;S-1-5-33)(A; LogFilePath : %SystemRoot%\System32\Winevt\Logs\System.evtx MaximumSizeInBytes : 15532032 LogMode : Circular OwningProviderName : ProviderNames : {ACPI, adp94xx, adpahci, adpu320...} ProviderLevel : ProviderKeywords : ProviderBufferSize : 64 ProviderMinimumNumberOfBuffers : 0 ProviderMaximumNumberOfBuffers : 16 ProviderLatency : 1000 ProviderControlGuid :

3. To read the log by the name "Microsoft-Windows-Dhcp-Client/Admin" in the “Application and Services Logs” category, enter the command as: PS C:\> get-winevent -logname 10

"Microsoft-Windows-Dhcp-Client/Admin" –Maxevents

As specified in the –maxevents parameter, the output above will return a maximum of 10 events only. 4. Enter the following command to list the providers that write to the System log. PS C:\> (get-winevent -listlog System).providernames

Task 4: Searching for Event Log entries The Event Logs can be queried based on several criteria. Inversely, you can filter based on the required properties to search for the occurrences of Events. 1. List the properties on the object returned by the Get-EventLog cmdlet. PS C:\> Get-EventLog system -Newest 2 | gm -MemberType property TypeName: System.Diagnostics.EventLogEntry Name ---Category CategoryNumber Container Data EntryType Index InstanceId MachineName Message ReplacementStrings Site Source TimeGenerated

Microsoft | Services

MemberType ---------Property Property Property Property Property Property Property Property Property Property Property Property Property

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 319 of 361

TimeWritten UserName

Property Property

2. List the properties on the “System.Diagnostics.Eventing.Reader.EventLogRecord” object returned by the Get-WinEvent cmdlet. PS C:\> Get-WinEvent system

-MaxEvents 2

| gm –membertype Property

TypeName: System.Diagnostics.Eventing.Reader.EventLogRecord Name ---ActivityId Bookmark ContainerLog Id Keywords KeywordsDisplayNames Level LevelDisplayName LogName MachineName MatchedQueryIds Opcode OpcodeDisplayName ProcessId Properties ProviderId ProviderName Qualifiers RecordId RelatedActivityId Task TaskDisplayName ThreadId TimeCreated UserId Version

MemberType ---------Property Property Property Property Property Property Property Property Property Property Property Property Property Property Property Property Property Property Property Property Property Property Property Property Property Property

PS C:\>

3. Searching for Event Log entries based on a search filter. get-eventlog -log system -source Time-Service | where {$_.eventID -eq 129 –and $_.message –like “*not found*"}

The command above will search the System log for source ‘Time-Service’ that has an Event ID ‘129’ and contains the “not found” message description. 4. Using the –FilterHashTable parameter with Get-WinEvent cmdlet. This uses a query in hash table format to select events from one or more event logs. Run the commands below to filter the ‘Windows Powershell’ logs for Event Id 400 logged since the previous day. C:\PS> $yesterday = (get-date) - (new-timespan -day 1) C:\PS> get-winevent -FilterHashTable @{LogName='Windows PowerShell'; id=’400’; StartTime=$yesterday}

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 320 of 361

Exercise 4: File and Folder ACL Management Objectives In this exercise, you will: 

Learn about how to read, copy, write and modify ACLs on Files & Folders using Windows Powershell cmdlets.

Scenario The file and folder access authorization is controlled using an access control list (ACL) on the object. The ACL is a list of entries (called the Access Control Entry: ACE) that identifies trustees and specifies the access rights allowed, denied, or audited for those trustees. In easier terms, the ACL specifies the permissions that users and user groups have to access the resource. Several commands line utilities like cacls, xcacls, icacls can be used to verify and modify the access permissions on files and directories. Windows PowerShell uses the cmdlets, Get-Acl und Set-Acl, to manage the permissions.

Task 1: Log on to the VM environment 1. Log on to the Windows 7 client as Contoso\Administrator

Task 2: Reading ACLS The cmdlet, Get-ACL, gets the security descriptor for a resource, such as a file, folder or registry key. While getting the access permissions on a file or folder, it creates a security descriptor object of the class System.Security.AccessControl.FileSecurity or system.Security.AccessControl.DirectorySecurity 1. Run the command below to get the ACL on the Windows directory. PS C:\>

get-acl $env:windir | ft -AutoSize –Wrap

2. To list the detailed access permissions, run the following command. PS C:\> (

get-acl C:\Windows).access | ft -wrap

Task 3: Copying ACLS The Set-Acl cmdlet changes the security descriptor on a file or a folder, to match the values in a security descriptor that you supply. The Set-Acl cmdlet, uses the -AclObject parameter to apply a security descriptor on the desired resource. In the following example, the ACL on a source directory would be copied to another directory. Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 321 of 361

Note: The folders named Source and Destination need to be created with different set of permissions before following the below steps.

1. Use the get-acl cmdlet to store the ACL of the source directory in a variable. $sourceacl = Get-acl c:\Source

2. Next apply the ACL in $sourceacl to the destination directory by running the following command. Set-acl –path c:\destination –aclObject $sourceacl

Task 4: Creating and modifying ACLS You can set permissions on files and folders by using the Set-ACL cmdlet but would also involve creating the security descriptor object specifying the System.Security.AccessControl.FileSystemAccessRule class. In this example, the ACL on the folder ‘c:\destination’ will be modified. 1. Get the current ACL of the folder using Get-ACL as follows: PS C:\> $destacl = Get-ACL c:\destination

2. Create the System.Security.AccessControl.FileSystemAccessRule object as follows: $aclrule = New-Object system.security.accesscontrol.filesystemaccessrule("administrators", "Read", "Allow")

3. Set the access rule object $aclRule to the existing access rule object $destacl using the SetAccessRule() method. PS C:\> $destacl.setaccessrule($aclrule)

4. Hence, the command below will apply the modified ACL to the destination folder. PS C:\> Set-ACL c:\destination –aclobject $destacl

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 322 of 361

Lesson 10 Hands-On : Registry, Event Log and ACL Management Objectives The objectives for this lab are: 

To search the Event Log for specific entries.



To check the registry of remote machine and modify values.



To configure permissions on a folder.

Prerequisites 

The lab requires a windows 7 client running in a domain environment.

Estimated time to complete this lab 30 minutes

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 323 of 361

Exercise 1: Reading Registry Information from a Remote Host Objectives In this exercise, you will: 

Read the registry values of a remote machine for Internet Explorer details.



Create a remote Reg key and create values.

Duration 15 minutes

Task 1: Log on to the VM environment Log on to Windows 7 Enterprise client as Contoso\Administrator with Password P@ssword

Task 2: Open Windows PowerShell Session On the windows task bar, locate the

icon. Click this icon.

The PowerShell window will open.

Task 3: Read the registry on a remote machine. 1. Create a file named c:\pshell\part1\lesson10\labs\lab1-ex1.ps1 with notepad, or the ISE. 2. On the first line enter the following: $servers = get-content c:\pshell\part1\lesson10\labs\servers.txt

3. On the next line, enter the following: $regpath = “software\microsoft\internet explorer”

4. On the next line, enter the following: Foreach ($server in $servers)

5. On the next line, enter the following: {

6. On the next line, enter the following: Write-host “Checking server: $server” –foregroundcolor green

7. On the next line, enter the following: $reg = [Microsoft.win32.registrykey]::openremotebasekey(‘LocalMachine’,$server)

8. On the next line, enter the following:

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 324 of 361

$regkey = $reg.opensubkey($regpath)

9. On the next line, enter the following: $values = $regkey.getvaluenames()

10. On the next line, enter the following: Write-host “Checking Internet Explorer details”

11. On the next line, enter the following: Foreach ($value in $values)

12. On the next line, enter the following: {

13. On the next line, enter the following: Write-host “$value : $($regkey.getvalue($value))”

14. On the next line, enter the following: }

15. On the next line, enter the following: }

16. Save your script: 17. Open the text file c:\pshell\part1\lesson10\labs\servers.txt You will see in this file contain SYDDC01and W7Client. 18. Now execute the saved script in PowerShell. You will see that the details for Internet Explorer for each machine displayed.

Task 4: Create a remote registry key and values 1. Now save the script file as lab10-Ex1a.ps1. 2. Change the line $regpath

= “software\microsoft\internet explorer”

to the code below:

$regpath = “software”

3. Modify the line $regkey

= $reg.opensubkey($regpath)

as follows:

$regkey = $reg.opensubkey($regpath,”true”)

Note: The parameter is added to the command to allow the key to be written to.

4. Replace the line $values

= $regkey.getvaluenames()

with the following code:

$contoso = $regkey.opensubkey("contoso",”true”)

5. On the next line, enter the following:

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 325 of 361

if ($contoso -eq $null) {$contoso = $regkey.createsubkey("contoso")}

The line above will create the registry key if it does not already exist. 6. On the next line, enter the following: $serialnumber = (get-wmiobject win32_bios -computer $server).serialnumber

The line above will extract as text the value of the serial number in bios. 7. On the next line, enter the following code. $contoso.SetValue("serialnumber",$serialnumber)

The line above will create the registry value, serial number, and the value will be the value in the $serialnumber variable. 8. On the next line, enter the following lines of code. $values = $contoso.getvaluenames() write-host "$server has the registry key HKLM:\software\Contoso if it didnt already" write-host "The following registry values exist under this key"

9. Delete the line Write-host

“Checking internet explorer details”

10. The next two lines of code should appear as follows: Foreach ($value in $values) {

Do not change these lines. 11. Modify the line of code Write-host following code.

“$value : $($regkey.getvalue($value))”

to the

Write-host “$value : $($contoso.getvalue($value))”

12. The following two lines of code should complete the script. } }

13. Save your script and execute it in PowerShell. You should now see displayed the registry key and the values for each machine.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 326 of 361

Exercise 2: Searching Event Logs for Events Objectives In this exercise, you will: 

Search the Eventlog for specific entries.

Duration 15 minutes

Task 1: Log on to the VM environment Log on to Windows 7 Enterprise client as Contoso\Administrator with Password P@ssword

Task 2: Open Windows PowerShell Session On the windows task bar, locate the

icon. Click this icon.

The PowerShell window will open.

Task 3: Create a script to search the eventlog. 1. Create a file named c:\pshell\part1\lesson10\lab10\lab10-Ex2.ps1 with notepad, or the ISE. 2. On the first line enter the following. $systemerrors= “c:\pshell\part1\lesson10\labs\systemerrors.csv”

3. On the next line, enter the following. $apperrors = “c:\pshell\part1\lesson10\labs\apperrors.csv”

The variables above will be used to store the paths to the files where error events from the system log and application will be written. 4. On the next line, enter the following. $sysevents = get-winevent –logname system | where-object {$_.id –eq 12} | selectobject –first 1 –property timecreated

The line above will search the eventlog for event ID 12, which is the operating system started. The select-object cmdlet using the –first parameter gets the last occurrence on this. This event ID can be used as a flag for the last boot as far as Eventlog entries go. 5. On the next line, enter the following. $lastreboot = $($sysevents.timecreated)

The line above extracts the time on the startup event. This will be used in the following lines to search for events after that time. 6. On the next line, enter the following.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 327 of 361

$sysevents = get-winevent -logname system | where-object {$_.Timecreated -gt $lastreboot} | where-object {$_.LevelDisplayName -eq 'Error' -or $_.leveldisplayname -eq 'Critical'}

The line above will search the system log for any errors that have occurred after the time in $lastreboot. 7. On the next line, enter the following. $count = ($sysevents | Measure-Object).count

8. On the next line, enter the following. If ($count –gt 0)

9. On the next line, enter the following. {

10. On the next line, enter the following. Write-host “$count Errors were found in the system eventlog. Details in the file $systemerrors”

11. On the next line, enter the following. $sysevents | export-csv $systemerrors –notypeinformation

12. On the next line, enter the following. }

This will close the first part of the if statement. 13. On the next line, enter the following. else

14. On the next line, enter the following. {

15. On the next line, enter the following. Write-host “No errors were found in the system eventlog after bootup at $lastreboot”

16. On the next line, enter the following. }

This will complete the if statement and else section. The code above will not only search for error in the system log, but will also export them to a csv file. If there are no errors then this will also be indicated. 17. Save your script and execute it in PowerShell. You will see that script will run and inform you of any errors that are in the system log. Note: You may not find any errors in the system after reboot. If you don’t see any errors detected then check the system log to see if this is actually the case.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 328 of 361

18. Open the c:\pshell\part1\lesson10\labs\systemerrors.csv using notepad. You will see the details of the event log entries in this file. 19. Open the script again in notepad or the ISE. 20. Copy the following lines of code. $sysevents = get-winevent -logname system | where-object {$_.Timecreated -gt $lastreboot} | where-object {$_.LevelDisplayName -eq 'Error' -or $_.leveldisplayname -eq 'Critical'} $count = ($sysevents | Measure-Object).count If ($count –gt 0) { Write-host “$count Errors were found in the system eventlog. Details in the file $systemerrors” $sysevents | export-csv $systemerrors -notypeinformation } else { Write-host “No errors were found in the system eventlog after bootup at $lastreboot” }

21. Paste these below the original section. 22. Change the code to match the following. In bold are the text that needs to change. $appevents = get-winevent -logname application | where-object {$_.Timecreated -gt $lastreboot} | where-object {$_.LevelDisplayName -eq 'Error' -or $_.leveldisplayname -eq 'Critical'} $count = ($appevents | Measure-Object).count If ($count –gt 0) { Write-host “$count Errors were found in the Application eventlog. Details in the file $apperrors” $appevents | export-csv $apperrors -notypeinformation } else { Write-host “No errors were found in the Application eventlog after bootup at $lastreboot” }

The above code should now look at the application log for Critical or Error levels since the last reboot. 23. Save your script and execute it in PowerShell. You will see that script will run and inform you of any errors that are in the system log. 24. Open c:\pshell\part1\lesson10\labs\apperrors.csv using notepad. You will see the details of the event log entries in this file.

Task 4: Optional Additional exercise. 1. Open the script in notepad or the ISE. 2. Modify the script to also look at the system log for warning entries and the application log warning events as well. You can use a similar process as above to perform these actions. Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 329 of 361

Note: You will need new variables and files to store the warning events in.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 330 of 361

Exercise 3: File and Folder ACL Management Objectives In this exercise, you will: 

Read the permissions on a folder.



Set the permissions on a folder.

Duration 15 minutes

Task 1: Log on to the VM environment Log on to Windows 7 Enterprise client as Contoso\Administrator with Password P@ssword

Task 2: Open Windows PowerShell Session On the windows task bar, locate the

icon. Click this icon.

The PowerShell window will open.

Task 3: Read folder permissions 1. In the PowerShell console, enter the following. New-item c:\userdata –type directory

This will create a new folder off the root of the C drive. This folder will inherit the default permissions. 2. In Windows explorer, check the folder permissions by right-clicking the folder, selecting Properties and checking the Security tab. Note: The permissions of the built in users group will have read and execute, list folder contents and read. These are inherited permissions so the ticks are grey.

3. In the PowerShell console, enter the following command. $acl = get-acl C:\userdata

This will read the access control lists for the object and assign them to the $acl variable. 4. Enter the following command. $acl.access

This will now display the access control lists for users and their permissions. In order to be able to change permissions such as removing a user from access, you need to remove the inherence from the parent folder.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 331 of 361

Task 4: Clear inheritance 1. Enter the following command to remove the inheritance. $acl.setaccessruleprotection($true,$true)

The above command modifies the access control list, however, this is not applied to the folder. To do this, you must set the ACL back to the folder. 2. Enter the following command to apply the modified ACL to the folder. $acl | set-acl c:\userdata

The permission inheritance will now be removed. 3. In Windows explorer, check the folder permissions by right-clicking the folder, selecting Properties and checking the Security tab. Note: The permission ticks are now solid black. This indicates that the permissions are set on the folder level and not inherited.

Task 5: Remove permissions 1. Enter the following command to retrieve the current ACLs for the folder. $acl = get-acl c:\userdata

Now you will have the current acl’s in the $acl variable. Now we can remove a specific users permissions from the object. First you must get the specific user ACL. 2. Enter the following command to get the BUILTIN\users ACL. $useracl = $acl.access | where {$_.identityreference -eq "BUILTIN\Users"}

3. Enter the following to view the ACL. $useracl

4. Enter the following to remove the ACL from the ACL list. $acl.RemoveAccessRule($useracl)

This will remove the builtin\users acl from the list of ACL’s. Once this is done the ACL list in the $acl variable can be applied to the object. 5. Enter the following to view the ACL list. $acl.access

6. Enter the following command to set the ACLs on the folder. $acl | set-acl c:\userdata

7. In Windows explorer, check the folder permissions by right-clicking the folder, selecting Properties and checking the Security tab. Note: The builtin\users group is now removed from the permission’s of the folder and now, you will grant the BUILTIN\users group full control to the folder.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 332 of 361

Task 6: Create an ACL 1. Enter the following to set the inheritance options for the folder. $inheritance = 3

The values for this can be 0 for none, 1 for containerinherit and 2 for ObjectInherit. The value used above is 3, which is both container and object inherit. 2. Enter the following to set the propagation options for the folder. $propagation = 0

The values for this can be 0 for none, 1 for NoPropagateInherit and 2 for Inheritonly. The value used above is 0, which is none. 3. Enter the following to create an array for the new ACL. $newacl = "BUILTIN\Users","fullcontrol",$inheritance,$propagation,"allow"

The above is an array of strings. This specifies the user account, the permissions required, the inheritance and propagation flags and finally if the permissions are allowed or denied. 4. Enter the following to create the new ACL object. $accessrule = new-object system.security.accesscontrol.filesystemaccessrule($newacl)

5. Enter the following command to add the new ACL object to the ACL list. $acl.AddAccessRule($accessrule)

6. Enter the following to list the ACLs. $acl.access

This will now display the ACL’s to be applied to the file. 7. Enter the following command to apply the ACLs to the object. $acl | set-acl c:\userdata

8. In windows explorer, check the folder permissions by right-clicking the folder, selecting Properties and checking the Security tab. You will note that the BUILTIN\Users will now have full control of the folder.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 333 of 361

PowerShell for the IT Administrator, Part 1 Lesson 11: PowerShell Remoting

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 334 of 361

Lesson 11 Demonstration : Remoting Introduction The majority of a system administrator's tasks involve managing a wide range of machines. Many tasks require the same action or information to be executed or obtained from multiple machines. This can be done locally at each machine. However, the most efficient way involves being able to manage these machines remotely and running your code from a centralized location. This lesson covers managing remote machines using the PowerShell Cmdlets supporting the -ComputerName parameter and using PowerShell remoting through Cmdlets that interact with the WinRM 2.0 service.

Objectives After completing this lesson you will be able to: 

Understand remote management without PowerShell remoting



Understand PowerShell remoting and WS-Management



Understand remoting requirements and configuration



Use the invoke-command for executing one-off commands



Work with PowerShell sessions to: 

Use a persistent remote session for executing a series of commands



Use an interactive remote session



Create a session configuration



Use background jobs with remoting



Understand remoting security and authentication, including: 

Active directory group policy object settings



Kerberos, Negotiate, CredSSP and Basic authentication



Traffic Encryption

Prerequisites 

A windows 7 workstation logged onto with administrator credentials



A domain controller, SYDDC01

Estimated time to complete this lesson 60 minutes

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 335 of 361

Exercise 1: Remote Management without PowerShell Remoting Objectives In this exercise, you will: 

Identify Cmdlets that have the -ComputerName parameter



Use Cmdlets with the -ComputerName parameter



Use WMI for remote management

Scenario In this exercise, you will understand remote management without the use of PowerShell remoting. This can be very useful in the environment where PowerShell remoting is not enabled.

Log on to the VM environment Log on to Windows 7 Enterprise client. 

Username; Contoso\Administrator



Password: P@ssword

Open Windows PowerShell Click the

icon on the Windows task bar

The PowerShell window will open.

Task 1: Identify Cmdlets with the -ComputerName Parameter 1. Type the following command. get-command | where { $_.parameters.keys -contains "computername" -and $_.parameters.keys -notcontains "session"}

This command lists all commands that contain the ComputerName parameter. It excludes any command that also contains ‘Session’ as a parameter. The Session parameter is associated with commands that relate to PowerShell remoting. The objective of this exercise is to perform remote management without the use of the PowerShell remoting feature.

Task 2: Using Cmdlets with the -ComputerName Parameter 1. Type the following command. get-eventlog -computername syddc01 -log system -newest 10

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 336 of 361

This command returns the ten newest events in the system event log on the domain controller machine (SYDDC01). 2. Type the following command. get-hotfix -computername syddc01,w7client

This command returns all the hotfixes on both the domain controller (SYDDC01) and the Windows 7 client. Note: Single or multiple machine names can be specified as parameter arguments to the ComputerName parameter.

Try the following command: get-hotfix -cn syddc01,w7client

Where, cn is an alias for the ComputerName parameter. 3. Type the following command. ”syddc01”,”w7client” > $home\documents\servers.txt

Now type the following command. get-hotfix -computername (get-content $home\documents\servers.txt)

The first command creates a servers.txt file in the current users documents directory using the $home automatic variable. The second command returns all the hotfixes on both the syddc01 and w7client machines. The get-content Cmdlet is used to retrieve the machine names from a text file in this example.

Task 3: Using WMI for Remote Management WMI also includes built-in remote management functionality that can be used independently from PowerShell remoting. 1. Type the following command. get-wmiobject win32_operatingsystem -computername syddc01

Operating System information related to machine syddc01 is displayed in the console. get-wmiobject win32_operatingsystem ` -computername syddc01,w7client

Operating system information related to both syddc01 and w7client is displayed in the console. The back tick or grave character (`) is used in this instance to escape the newline character that separates the first part of the command from the second part. This can be useful to facilitate readability when typing long commands into either a console or a script file.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 337 of 361

Note: Either the machine name or IP address can be specified as the parameter arguments for the ComputerName parameter.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 338 of 361

Exercise 2: Enable PowerShell Remoting Objectives In this exercise, you will: 

Verify if PowerShell remoting is available



Enable PowerShell remoting

Scenario PowerShell remoting is useful for running commands or scripts that do not have built-in remote management capabilities. PowerShell remoting allows you to remotely manage machines using the underlying Web Services for Management (WS-Management) protocol implemented in the WinRM service. WS-Management is an industry standard management protocol based on the Simple Object Access Protocol (SOAP). The WS-Management protocol was developed by a group of hardware and software manufacturers as a public standard for remotely exchanging management data with any computer device that implements the protocol. WinRM 2.0 is Microsoft implementation of the WS-Management protocol.

PowerShell Remoting Requirements The following components are required on both the local machine and remote machine(s): 

Windows PowerShell 2.0 or later



Microsoft .NET Framework 2.0 or later



Windows Remote Management (WinRM) 2.0

WinRM 2.0 is by default included in Windows 7 and in Windows Server 2008 R2. For operating systems other than Windows 7 and Windows 2008 R2 Server the Windows Management Framework package can be downloaded from http://support.microsoft.com/default.aspx/kb/968929. This package will install Windows PowerShell 2.0, WinRM 2.0, and BITS 4.0. The update can be installed on the following operating systems: 

Windows Server 2008 Service Pack 2 (SP2)



Windows Vista SP 1 and 2



Microsoft Windows Server 2003 SP 2



Microsoft Windows XP SP 3

An administrator must explicitly enable and configure PowerShell remoting before it can be used.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 339 of 361

Note: Windows PowerShell Integrated Scripting Environment (ISE) and the OutGridview Cmdlet require the Microsoft .NET Framework 3.5 with Service Pack 1. The Get-WinEvent cmdlet requires the Microsoft .NET Framework 3.5 or greater. This version of the Microsoft .NET Framework is however not required for PowerShell remoting.

Log on to the VM environment Log on to Windows 7 Enterprise client. 

Username; Contoso\Administrator



Password: P@ssword

Open Elevated Windows PowerShell Session To open an elevated Windows PowerShell session: 1. Right-click the

icon on the Windows task bar.

2. Select Run As Administrator. 3. Click Yes if a User Account Control Prompt appears The PowerShell window will open.

Task 1: Verify PowerShell Remoting 1. Type the following command to verify whether or not the service is running. get-service -computername syddc01,w7client | where{$_.name -eq "winrm"} | select name,machinename,status | sort machinename | ft -autosize

Task 2: Enable PowerShell remoting 1. Type the following command to enable PowerShell remoting. enable-psremoting

2. Type Y to continue. 3. Type the following command to verify that the service is running get-service winrm

4. Type the following command to view additional details about the WinRM client configuration. winrm get winrm/config/client

5. Repeat the steps above on machine syddc01. Note: The enable-psremoting Cmdlet does not support the ComputerName parameter.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 340 of 361

Exercise 3: Enable PowerShell Remoting with the Active Directory Group Policy Object (GPO) Objectives In this exercise, you will: 

Explore the AD GPO configuration settings for WinRM.

Scenario The Enable-PSRemoting Cmdlet does not include support for the ComputerName parameter. As a result, it is not an efficient solution to enable PowerShell remoting for large numbers of machines. Two common methods to do this are: 1. Use the Enable-PSRemoting Cmdlet with the -Force switch to suppress user prompts in a logon script. 2. Use group policy objects. Example GPO Configuration: Computer Configuration Administrative Templates Network/NetworkConnections/Windows Firewall/Domain Profile Policy Name - Windows Firewall: Define inbound Port Exceptions Setting - Enabled Define Port Exceptions - “5985:TCP:*:enabled:WS-Man Listener Port 5985” Windows Components/Windows Remote Management (WinRM)/WinRM Service Policy Name - Allow automatic configuration of listeners Setting – Enabled IPv4 Filter – * IPv6 Filter – * Windows Components/Windows Remote Shell Policy Name - Allow Remote Shell Access Setting – Enabled

Log on to the VM environment Log on to Windows 7 Enterprise client. 

Username; Contoso\Administrator



Password: P@ssword

Task 1: Open GPO and Explore Configuration Settings 1. On the domain controller SYDDC01, type gpedit.msc at a command prompt. The Group Policy Object Editor window opens.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 341 of 361

2. Look for the Doman Profile GPO under Administrative Templates, Network, Network Connections and Windows Firewall. The Windows Firewall: Define inbound Port Exceptions setting can be used to enable an inbound firewall exception for the WS-Management listener service on port 5985 for the TCP protocol. 3. Look for the Windows Remote Management and Windows Remote Shell GPO’s under Administrative Templates and Windows Components. The Allow automatic configuration of listeners setting allows automatic configuration of the WS-Management listener port for all machines. A wildcard (*) for each filter allows messages from many remote machines. This can alternatively be populated with a comma-separated list or dash-separated range of IP v4 or IP v6 addresses. The Allow Remote Shell Access setting allows remote shell access to the machine. Note: The Windows Remote Management GPO also allows setting the authentication protocol. The options are Kerberos, Negotiate, CredSSP and Basic. The default authentication protocol is Kerberos for domain joined machines and NTLM for non-domain joined machines. The authenticating protocol (either Kerberos or NTLM) is dynamically selected using negotiate authentication. Disabling negotiate authentication will effectively disable NTLM authentication. All WinRM traffic is encrypted by default. Unencrypted traffic can be enabled using the ‘Allow unencrypted traffic’ GPO setting.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 342 of 361

Exercise 4: Execute a Single Remote Command or Script Objectives In this exercise, you will: 

Execute a single remote command



Execute a single remote script



Use a background job to run a single remote command

Scenario To run a command on remote machines on a one-time-only basis, use Invoke-Command. This Cmdlet can accept a list of remote computer names in its –ComputerName parameter. The command to actually run on the remote machine is in the form of a scriptblock and therefore, enclosed in curly braces.

Log on to the VM environment Log on to Windows 7 Enterprise client. 

Username; Contoso\Administrator



Password: P@ssword

Open Elevated Windows PowerShell Session To open an elevated Windows PowerShell session: Right-click the

icon on the Windows task bar.

1. Select Run As Administrator. 2. Click Yes if a User Account Control Prompt appears. The PowerShell window will open.

Task 1: Execute a Single Remote Command 1. Type the following command. invoke-command -computername syddc01,w7client -scriptblock {get-process}

Process information related to both the syddc01 and w7client machines are returned. Note that a PSComputerName column is added to the output.

Task 2: Execute a Single Remote Script 1. Type the following command. ”get-process” > $home\documents\single_remote_script.ps1

2. Type the following command. Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 343 of 361

invoke-command -computername syddc01,w7client -filepath $home\documents\single_remote_script.ps1

The first command creates a single_remote_script.ps1 file in the current users documents directory using the $home automatic variable. The second command uses the -FilePath parameter to specify the newly created script that is stored locally. The script returns process information related to both the syddc01 and w7client machines.

Task 3: Use a Background Job to Run a Single Remote Command 1. Type the following command. $command = {gwmi -query “select name,status,manufacturer,biosversion from win32_bios” | fl name,status,manufacturer,biosversion,pscomputername}

This command stores a query in a variable for use in the next command. 2. Type the following command $job = invoke-command -computername syddc01,w7client -ScriptBlock $command ThrottleLimit 2 -AsJob

Jobs can also be used in conjunction with PowerShell remoting. A long-running job run against many machines can be executed in a background thread so that control is immediately returned to the shell and the user can continue with another task. To do this, include the -AsJob parameter in the Invoke-Command Cmdlet and save the command to a variable reference. 3. Type the following command. $job

This command retrieves information about the job. 4. Type the following command. $job.childjobs

To view the results of child jobs, use the childjobs property of the $job object. 5. Type the following command. receive-job -name job2 -keep

Use the Receive-Job Cmdlet to view the information returned from each remote machine. The keep parameter is used to keep the data available for future retrieval using the receive-job Cmdlet. Note: It is possible for the job number to be different. Take note of the job names that are displayed after step 4 above.

6. Type the following command. get-job | remove-job

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 344 of 361

This command removes all jobs.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 345 of 361

Exercise 5: Create a Persistent Session to Execute a Series of Remote Commands Objectives In this lesson, you will: 

Create a persistent session and then proceed to run commands and scripts against this session



Use variables created in one command from another command that runs from the same session

Scenario The Invoke-Command approach is useful for one-off commands. However, if you want to run a series of commands against remote machines and store variables that you can access later, you need to use the PowerShell remoting concept of a session, which is persisted between commands. The New-PSSession Cmdlet enables the creation of a new persistent PowerShell run space on a remote computer, which is not destroyed every time a command is issued. You can specify a single or multiple machines to create sessions with and run a command against each session.

Log on to the VM environment Log on to Windows 7 Enterprise client. 

Username; Contoso\Administrator



Password: P@ssword

Open Elevated Windows PowerShell Session To open an elevated Windows PowerShell session: 1. Right-click the

icon on the Windows task bar.

2. Select Run As Administrator. 3. Click Yes if a User Account Control Prompt appears. The PowerShell window will open.

Task 1: Create and Use a Persistent Session 1. Type the following command. $mysession = new-pssession -computername syddc01,w7client

This command specifies multiple machines to create a session with. A variable is used to store the session information.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 346 of 361

2. Type the following command to view information related to the session. $mysession

Note the session identifiers. 3. Type the following command. invoke-command -session $mysession -scriptblock {$env:processor_architecture}

This command uses the session that was created in step 1 and retrieves the processor architecture for both the syddc01 and w7client machines. Note that the session is not destroyed and can be used again. 4. Type the following command. $session1 = get-pssession -id 1

The Get-PSSession Cmdlet allows you to get a reference to these sessions by their identifier property. 5. Type the following command to list information related to the session identifier. $session1

6. Type the following command. $session2 = get-pssession -id 2

The Get-PSSession Cmdlet allows you to get a reference to these sessions by their identifier property. 7. Type the following command to list information related to the session identifier. $session2

8. Type the following command to run a command against a specific session identifier as opposed to against all session identifiers that were created during step 1 in the $mysession variable. invoke-command -session $session1 -scriptblock {$env:computername}

9. Type the following command to return the ComputerName that relates to the other session. invoke-command -session $session2 -scriptblock {$env:computername}

10. In this example, you will create a variable in one command and then demonstrate using that variable in a subsequent command. A. Type the following command. invoke-command -session $session2 -scriptblock {$date = get-date displayhint time}

B. Type the following command to use the variable created in Step 10 A. invoke-command -session $session2 -scriptblock {$date} Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 347 of 361

11. Type the following command to remove all sessions. get-pssession | remove-pssession

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 348 of 361

Exercise 6: Create an Interactive Session with a Remote Machine Objectives In this exercise, you will: 

Create and use an interactive PowerShell remoting session

Scenario The last type of remote session is an interactive remote session. The Enter-PSSession Cmdlet automatically creates a remote session object and allows you to enter commands as if you were physically sitting in front of the PowerShell console of the remote computer. The Exit-PSSession Cmdlet takes you out of the remote interactive session.

Log on to the VM environment Log on to Windows 7 Enterprise client. 

Username; Contoso\Administrator



Password: P@ssword

Open Elevated Windows PowerShell Session To open an elevated Windows PowerShell session: 1. Right-click the

icon on the Windows task bar.

2. Select Run As Administrator. 3. Click Yes if a User Account Control Prompt appears. The PowerShell window will open.

Task 1: Create and use an interactive PowerShell remoting session 1. Type the following command to create an interactive session with the syddc01 machine. enter-pssession -computername syddc01

Note: The prompt changes to [syddc01]: PS c:\users\administrator\documents>

2. Type the following commands to confirm the computer name. Note that using this session is just like being at the console of the syddc01 machine. $envvar = $env:computername

$envvar

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 349 of 361

3. Type the following command to close the session. exit-pssession

4. Type the following command to remove all sessions. get-pssession | remove-pssession

Task 1: Enter an Existing Persistent Session for Interactive Access 1. Type the following command to create a reference to a session. $mysession = new-pssession -computername syddc01

2. Type the following command to enter the session using an existing session reference. enter-pssession –session $mysession

3. Type the following commands to confirm the computer name. Note that using this session is just like being at the console of the syddc01 machine. $envvar = $env:computername

$envvar

4. Type the following command to close the session. exit-pssession

5. Type the following command to remove all sessions. get-pssession | remove-pssession

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 350 of 361

Exercise 7: Create a Session Configuration Objectives In this lesson, you will: 

Create and use a session configuration

Scenario A very useful advanced feature of remote sessions is the ability to create constrained configuration environments to which remote users can connect. The Register-PSSessionConfiguration cmdlet is run on a local machine to create a new configuration name with a number of configuration options.

Log on to the VM environment Log on to Windows 7 Enterprise client. 

Username; Contoso\Administrator



Password: P@ssword

Open Elevated Windows PowerShell Session To open an elevated Windows PowerShell session: 1. Right-click the

icon on the Windows task bar.

2. Select Run As Administrator. 3. Click Yes if a User Account Control Prompt appears. The PowerShell window will open.

Task 1: Create a New Customized Session Configuration 1. Type the following command to view the configured sessions on this machine. get-pssessionconfiguration | format-list -property name, permission

2. Type the following command get-variable

Note: The PSSessionConfigurationName variable value. This is the default configuration for the machine. The default configuration is: http://schemas.microsoft.com/powershell/Microsoft.PowerShell

3. A configuration script file is required. Type the following command to display an example of such a script. type $home\documents\remoteadmin_startupscript.ps1

The contents of the file are shown below: Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 351 of 361

# Create a list of cmdlets you want to be available in this configuration: $arrcmdlets = @("get-command","get-service","get-process") # Set private visibility for all other cmdlets: get-command | where-object {$arrcmdlets -notcontains $_.Name} | foreachobject{ $_.Visibility = "Private" } # Turn off the user’s ability to use language statements: $ExecutionContext.SessionState.LanguageMode="NoLanguage"

4. Type the following command. Register-PSSessionConfiguration -Name RemoteAdmin -StartupScript c:\users\administrator\documents\RemoteAdmin_StartupScript.ps1 MaximumReceivedDataSizePerCommandMB 20 -MaximumReceivedObjectSizeMB 2

5. Type Y to confirm the action and Y again to confirm restarting the WinRM service. This command will create a new session configuration with the name. RemoteAdmin. The script file from the previous step is specified as the configuration source. The MaximumReceivedDataSizePerCommandMB parameter limits the amount of data that can be sent to the machine in any single remote command. The MaximumReceivedObjectSizeMB parameter limits the amount of data that can be sent to the machine in any single object. 6. Type the following command again to view the configured sessions on this machine now. get-pssessionconfiguration | format-list -property name, permission

Note that permissions have not been configured for the new RemoteAdmin session configuration. 7. Type the following command to configure permissions for the new RemoteAdmin session configuration. set-pssessionconfiguration remoteadmin –showsecuritydescriptorui

8. Type Y to confirm the action. 9. Select the checkbox to Allow Execute/Invoke permissions for the Administrators group. Note: In a production environment, a more appropriate group will typically be added and assigned permissions in this step.

10. Click Ok. 11. Type Y to confirm restarting the WinRM service. 12. Type the following command again to view the configured sessions on this machine now. get-pssessionconfiguration | format-list -property name, permission Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 352 of 361

Permissions have now been configured for the RemoteAdmin session configuration.

Log on to the VM environment Log on to Windows 7 Enterprise client. 

Username; Contoso\Administrator



Password: P@ssword

Open Elevated Windows PowerShell Session There are several different ways to open windows PowerShell. Each of these has its own purpose. The first one we will use is most likely the simplest. On the windows task bar locate the

icon.

This is the PowerShell icon. Right-Click on this icon, select Run As Administrator and click Yes if a User Account Control prompt is presented. The PowerShell window will open. You will notice it looks quite different to the standard command prompt. It should have a blue background and white text. It will also have the text PS c:\users\administrator> The PS also tells you that you are using a PowerShell shell and not the CMD Shell.

Task 2: Use the New Customized Session Configuration 1. Type the following command to create a new remote session that uses the new RemoteAdmin configuration to the SYDDC01 machine. $s = new-pssession -computername SYDDC01 -configurationname remoteadmin

2. Type the following command to return a list of all the available commands. invoke-command -session $s -scriptblock {get-command}

Note: Only three commands (Get-Command, Get-Process and Get-Service) specified in the script file remoteadmin_startupscript.ps1 are available.

3. Type the following command to test use of language elements (Do…While). invoke-command -session $s -scriptblock {$i=0;do {get-process} while ($i -eq 0)}

Note that this command fails as expected. The statement: $ExecutionContext.SessionState.LanguageMode="NoLanguage" in the remoteadmin_startupscript.ps1 disables use of language elements. 4. Type the following command to test using pipeline filtering and formatting commands. Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 353 of 361

invoke-command -session $s -scriptblock {get-process} |where-object {$_.handle -gt 1000} | select-object name,handles,pscomputername

Note that these still work, even though the associated Cmdlets have been disabled. 5. Type the following command to remove all sessions from the machine. get-pssession | remove-pssession

Log on to the VM environment Log on to Windows 7 Enterprise client. 

Username: Contoso\Administrator



Password: P@ssword

Open Elevated Windows PowerShell Session There are several different ways to open windows PowerShell. Each of these has its own purpose. The first one we will use is most likely the simplest. On the windows task bar locate the

icon.

This is the PowerShell icon. Right-Click on this icon, select Run As Administrator and click Yes if a User Account Control prompt is presented. The PowerShell window will open. You will notice it looks quite different to the standard command prompt. It should have a blue background and white text. It will also have the text PS c:\users\administrator> The PS also tells you that you are using a PowerShell shell and not the CMD Shell.

Task 3: Remove a Customized Session Configuration 1. Type the following command to remove the RemoteAdmin session configuration from the machine. unregister-pssessionconfiguration remoteadmin

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 354 of 361

Lesson 11 Hands-On : Remoting Objectives After completing this lab you will be able to: 

Use PowerShell remoting to execute commands remotely



Use background jobs with remote tasks



Create a customized session configuration for PowerShell remoting

Prerequisites The lab requires a Windows 7 client running in a domain environment.

Estimated time to complete this lab 30 minutes

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 355 of 361

Exercise 1: Execute Remote Commands Objectives In this exercise, you will: 

Execute commands on remote machines using single remote commands.

Task 1: Log on to the VM environment Log on to Windows 7 Enterprise client. 

Username; Contoso\Administrator



Password: P@ssword

Task 2: Open Windows PowerShell Session To open Windows PowerShell: Click the

icon on the Windows task bar

Task 3: Enable PSremote 1. In the PowerShell console, type the following command to enable PSremoting Enable-psremoting

2. Answer Y when prompted to continue. You will notice that WinRM has already been enabled on the virtual machine. 3. Type the following command to run ipconfig on the machines. Invoke-command –computername syddc01,w7client –scriptblock {ipconfig}

This will return the ipconfig information from both machines. 4. Type the following command to get details of the lsass process. invoke-command -computername syddc01,w7client -scriptblock {get-process -name lsass}

You will see an extra column (PSComputerName), as the information is coming from invoke-command. 5. Type the following command to get the computer system information from WMI Invoke-command –computername syddc01,w7client –scriptblock {get-wmiobject win32_computersystem}

6. Type the following command to create a PSCredential object $Credentials = Get-Credential

Enter the following details:  Microsoft | Services

Username; contoso\administrator © 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 356 of 361



Password: P@ssword

7. Type the following command to use the credentials with invoke-command Invoke-command –computername syddc01 –credential $Credentials –scriptblock {get-process}

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 357 of 361

Exercise 2: Execute Commands via Sessions Objectives In this exercise, you will: 

Read the registry values of a remote machine for internet explorer details



Create a remote reg key and create values

Task 1: Log on to the VM environment Log on to Windows 7 Enterprise client. 

Username; Contoso\Administrator



Password: P@ssword

Task 2: Open Windows PowerShell Session To open Windows PowerShell: Click the

icon on the Windows task bar

Task 3: Create Remoting Sessions 1. In the PowerShell console, type the following command to create reusable sessions. $mysessions = New-pssession –computername syddc01,w7client

2. Type the following command to view the sessions $mysessions

3. Type the following command to execute commands using the session Invoke-Command -Session $mysessions -command {$env:computername}

The above command will return the computername of the computers. Since this is a reusable session, you can create remote variables. 4. Type the following command to create a remote variable Invoke-command –session $mysessions –scriptblock {$lastboot = (get-eventlog – logname system | where-object {$_.eventid –eq 6005} | select-object –first 1 – property timegenerated).timegenerated}

5. Type the following command to view the remote variables. Invoke-command -session $mysessions -scriptblock {"$env:computername : $lastboot"}

6. Type the following command to create more remote variables. Invoke-command –session $mysessions –scriptblock {$intevents = 20;$winrmlog=”Microsoft-Windows-WinRM/Operational”}

7. Type the following command to read events from the WinRM eventlog. Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 358 of 361

Invoke-command –session $mysessions –scriptblock {get-winevent –logname $winrmlog –maxevents $intevents}

8. Type the following command to get the w7client session. Get-PSSession | where {$_.computername -like "w7client"}

You will now see the details for the psession on w7client. Note that is currently open. 9. Type the following command to remove the session. Get-PSSession | where {$_.computername -like "w7client"} | Remove-PSSession

10. Type the following command to view the details of the $mysessions variable. $mysessions

You will now see the details for both sessions. Note that because you removed the session for w7client, it is now displayed as closed with availability as none. 11. Type the following command to use the sessions. Invoke-command -session $mysessions -scriptblock {"$env:computername : $lastboot"}

You will now receive an error from w7client as the session is closed. The session is still available for syddc01 and you will receive a result from that machine. 12. Type the following to separate the sessions. $activesessions = Get-PSSession | where {$_.state –eq “Opened” –and $_.availability –eq “Available”}

13. Type the following to ensure you have an active session. $activesessions

14. Type the following command to test the active sessions. Invoke-command -session $activesessions -scriptblock {"$env:computername : $lastboot"}

This will now run without errors as only active sessions are stored in the $activesessions variable.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 359 of 361

Exercise 3: Interactive Remote Console Objectives In this exercise, you will: 

Read the permissions on a folder



Set the permissions on a folder

Task 1: Log on to the VM environment Log on to Windows 7 Enterprise client. 

Username; Contoso\Administrator



Password: P@ssword

Task 2: Open Windows PowerShell Session To open Windows PowerShell: Click the

icon on the Windows task bar

Task 3: Create a share on remote machine 1. In the PowerShell console, type the following command to list the shares available on syddc01. Get-wmiobject win32_share -computer syddc01

Note the list of shares. There is no software share currently. 2. Type the following command to test the share. Test-path \\syddc01\software

You will get a false result as the share does not currently exist. 3. In the PowerShell console, type the following. Enter-pssession syddc01

This will now enter an interactive remote console on syddc01. Note that the prompt has changed to [syddc01]: PS C:\Users\Administrator\Documents> This indicates that the console is now operating on syddc01. 4. In the console, type the following command to change location. Set-location c:\shares

5. Type the following command to create a new directory. New-item –name software –type directory

This will create a directory on the syddc01 server. Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

Page 360 of 361

6. Type the following command to create an instance of the WMI class. $wmiclass = [wmiclass]’win32_share’

The line above creates an instance of the class win32_share with the wmiclass type alias. This is required as using get-wmiobject will not expose the create method. 7. Type the following command to create a new share on the server. $wmiclass.Create("C:\shares\software","software",0)

The command above creates the share. The first part of the create method call is the share path, the second part is the name of the share and the third part is the type of share. Note: A type 0 is a disk share.

8. Type the following command to exit the remote session. Exit-pssession

You will notice that the prompt now returns to PS C:\Users\administrator> indicating that you are now working on the local machine. 9. Type the following command to list the shares on syddc01. Get-wmiobject win32_share -computer syddc01

You will notice that there is now a software share. 10. In the PowerShell console, type the following command to test the share. Test-path \\syddc01\software

You will now get a true result as the share now exists.

Microsoft | Services

© 2012 Microsoft Corporation Microsoft Confidential

ITOE Educate

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF