Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 43

Module 3

Core Windows
PowerShell Cmdlets

Module Overview
In this module, you will learn to:
Recognize Windows PowerShells core cmdlets
Sort, group, count, measure, and select objects in the

pipeline

Import and export objects from various sources


Compare sets of objects

Lesson 1: Core Cmdlets for Everyday Use


This lesson teaches you to:
Recognize Windows PowerShell core cmdlets

Sort objects in the pipeline


Group objects in the pipeline
Count and measure objects in the pipeline

Select specific properties of objects in the pipeline


Select a subset of the objects in the pipeline
Import and export objects to and from delimited files

Import and export objects to and from XML files


Compare sets of objects, including objects imported from

a delimited or XML file

The Core Cmdlets


Data Manipulation

Sort-Object

Group-Object

Measure-Object

Select-Object

Compare-Object

These cmdlets manipulate data


from other cmdlets

Importing and Exporting Data

Import-CSV

Export-CSV

Import-CliXML

Export-CliXML

These cmdlets import/export


data from other formats

Objects and Members


An Object

Is a general software term that typically refers to some selfcontained piece of functionality

A PowerShell cmdlet

Often consumes an object to accomplish some task

Typically produces an object as a result, or manipulates other


objects to produce an object

For example,
Object -> Cmdlet -> Object
The Event Log -> Get-EventLog -> An Event Log View

An object is superior to a simple text result, because it can

be sorted, grouped, measured, selected, and so forth

Sorting Objects
The Sort-Object cmdlet

Enables you to change the order in which objects are listed.

Takes any type of object as input.

Can specify the name of one or more properties to be sorted.

Uses ascending sort order by default.

Uses the -descending parameter to sort descending.

Operates on actual property values, which are not always


displayed. PowerShell can convert values to text strings.
Get-Service | Sort-Object status
Get-Service | Sort-Object status descending

Get-Service | Sort-Object status, name


Sort is a built-in alias for Sort-Object.

Grouping Objects
The Group-Object cmdlet

Provides a way to place objects into different groups

Enables manipulation of results by group

Examines a designated object property and creates a new


group of objects for each property value it encounters

Is useful only when object properties have repetitive values

Can be used for counting the number of objects in a group

Get-Service | Group-Object status

Demonstration: Sorting and Grouping Objects


Using Sort-Object in the shell
Using Group-Object in the shell

Measuring Objects
The Measure-Object cmdlet

Counts the number of objects piped to it

Measures specific aggregate values for numeric properties

-average

-maximum

-minimum

-sum

Consumes its input objects, meaning that they are no longer


in the pipeline

Is typically used as the last PowerShell command in a series of


pipelined commands
Get-Process | Measure-Object
Get-Process | Measure-Object property VM
average sum minimum -maximum

Selecting Objects
The Select-Object cmdlet

Is used for two distinct purposes:

1. Selecting a subset of objects: -first, -last, -skip


Get-Process | Select-Object first 10
2. Selecting specified properties of an object
Get-Process | Select-Object name,ID,VM,PM

Combinations of its two purposes are also useful

Get-Process | Select-Object name,ID first 10

Demonstration: Measuring and Selecting Objects


Using Measure-Object in the shell
Using Select-Object in the shell

Importing and Exporting Data to CSV and XML


Sometimes data needs to come from or be used by other

sources

Imported-from/exported-to non-PowerShell aware sources

Imported-from/exported-to databases, spreadsheets, and so


forth

PowerShell natively imports/exports data to and from CSV

and XML file formats

Import-CSV, Export-CSV, Import-CliXML, Export-CliXML

Get-EventLog Security newest 20 | Export-CSV new-events.csv


Get-Process | Sort VM desc | Select First 10 | Export-CSV
top-vm.csv

Import-CliXML procs.xml | Get-Member


Remember: Exported data is no longer a live object

Demonstration: Working with CSV Files


Use Import-CSV in the shell
Use Export-CSV in the shell

Comparing Objects
The Compare-Object cmdlet

Provides the capability of comparing two sets of objects

Is used for comparing values of similar properties or object


characteristics

Provides garbage results if two dissimilar elements are


compared

Correctly using Compare-Object can be tricky.


Try exporting a snapshot of running services, then change
a service, and then compare the two:
Get-Service | Export-CliXML service-baseline.xml
Start or stop a service
Compare-Object (Get-Service) (Import-CliXML
service-baseline.xml)

Demonstration: Comparing Objects


Use Compare-Object in the shell

Lab A: Using the Core Cmdlets


Exercise 1: Sorting and Selecting Objects
Exercise 2: Retrieving a Number of Objects and Saving to

a File

Exercise 3: Comparing Objects Using XML


Exercise 4: Saving Objects to a CSV File
Exercise 5: Measuring a Collection of Objects

Logon information
Virtual machine

LON-DC1

LON-SVR1

Logon user name

Contoso\Administrator Contoso\Administrator Contoso\Administrator

Password

Pa$$w0rd

Pa$$w0rd

Estimated time: 30 minutes

LON-SVR2

Pa$$w0rd

Lab Scenario
You work as a system administrator in a small company
The company you work with has not invested in an

enterprise-class monitoring solution

As a result, you have to do a lot of performance

monitoring and capacity management/trending

One of your duties is to log in to servers and gather some

basic statistics, which you do on an almost daily basis

You would like to keep a record of their current status by

saving a file locally on the server as a future reference

Lab Review
How might sorting work with numbers versus strings?
Can you think of other delimiters you may want to use

with Export-Csv?

Is there a difference between saving objects to a variable

versus saving them to XML formatted file?

Thinking about objects having properties and methods, if

an object is saved to a file, is anything lost?

Lesson 2: Comparison Operators, Pipeline


Filtering, and Object Enumeration
This lesson teaches you to:
Explain the purpose and use of basic comparison operators

Explain the purpose and use of Boolean operators


Interactively compare two values or objects to each other
Filter objects out of the pipeline based on criteria

Identify the best place to apply filtering given performance

criteria

Enumerate objects in the pipeline and perform an action

with or against each object

Understanding Comparison Operators


Comparisons in PowerShell are used to determine True

versus False. For example, in the non-PowerShell world:


4 > 10 is False
10 = 5 is False
15 15 is True

PowerShell defines two special objects: $True, $False.

PowerShell will execute comparisons from the command line:


4 -gt 10
False
10 eq 5
False
15 cle 15
True

What Are the Comparison Operators?


Main comparison operators:
-eq : Equal to
-ne : Not equal to
Case-insensitive operators
-le : Less than or equal to
(not commonly used)
-ge : Greater than or equal to
-ieq : Equal to
-gt : Greater than
-ine : Not equal to
-lt : Less than
-ile : Less than or equal to
Case-sensitive operators:
-ceq : Equal to
-cne : Not equal to
-cle : Less than or equal to
-cge : Greater than or equal to
-cgt : Greater than
-clt : Less than

-ige : Greater than or equal to


-igt : Greater than
-ilt : Less than

Boolean Operators
The Boolean operators (-and, -or, -not) are used in more-

complex comparisons, working with complete subcomparisons on each side

-and returns $True when both sides are true

-or returns $True when either or both sides are true

-not reverses True and False


4 gt 10 or 10 gt 4
4 gt 10 and "Hello" ne "Hello"
(4 gt 10 and (10 lt 4 or 10 gt 5) and 10 le 10)
(-not 5 eq 5) and (10 eq 10)

Parenthesis group sub-comparisons and define an order of

execution

The most deeply-nested parenthesis are executed first, and


the execution is completed from left to right

Demonstration: Working with Basic Comparison


Operators
Use basic comparison operators in the shell

Understanding Pipeline Filtering


The Where-Object cmdlet

Is used to remove some objects from the pipeline

Removes objects based on specified criteria

Passes remaining objects to cmdlets further down the pipeline

Where-Object uses the special placeholder variable $_ to

signify the current pipeline object for comparison

Get-Service | Where-Object { $_.Status eq "Running" }

Caution: Using Where-Object requires processing each

value in the cmdlets result, which can be computationally


expensive

Use cmdlet filtering before Where-Object where possible

Demonstration: Understanding Pipeline Filtering


Use Where-Object in the shell

Understanding Object Enumeration


The ForEach-Object cmdlet

Provides a way to perform an action against a set of objects

As with Where-Object, uses $_ as a placeholder for the current


piped-in object

Typically uses a script block to contain the action


Get-Service | Where-Object { $_.Status eq "Stopped" }
| ForEach-Object { $_.Start() }

Remember: ForEach-Object is computationally expensive

Consider using ForEach-Object only when an existing cmdlet


cannot accomplish your task on its own against a batch of
objects

Demonstration: Object Enumeration


Use ForEach-Object in the shell

Lab B: Filtering and Enumerating Objects in


the Pipeline
Exercise 1: Comparing Numbers (Integer Objects)
Exercise 2: Comparing String Objects

Exercise 3: Retrieving Processes from a Computer


Exercise 4: Retrieving Services from a Computer
Exercise 5: Iterating Through a List of Objects

Logon information
Virtual machine

LON-DC1

LON-SVR1

Logon user name

Contoso\Administrator Contoso\Administrator Contoso\Administrator

Password

Pa$$w0rd

Pa$$w0rd

Estimated time: 30 minutes

LON-SVR2

Pa$$w0rd

Lab Scenario
You are a system administrator
One of your tasks in the morning as your shift is starting is

to check the status of the processes and services for the


servers you are responsible for

Lately, you have a particular service that is installed on

several computers that have been having issues

Your corporate monitoring solution has not always been

alerting that the service has stopped running

Lab Review
What if you wanted to filter a list of processes that started

with s* and with e*? Would you use Where-Object or


Name?

When working with remote services, are there any

advantages in using the Name parameter versus using


Where-Object?

What might interfere with doing any kind of query of a

remote computer?

Lesson 3: Advanced Pipeline Techniques


Explain the difference between pipeline input ByValue and

ByPropertyName

Pipe objects to a cmdlet so that input objects and

properties bind to a specified parameter of the cmdlet

Modify objects in the pipeline to attach a new property

having the same value as an existing property to facilitate


pipeline parameter binding ByPropertyName

Explain the use of the passthru cmdlet parameter

Parameters: The Key to the Pipeline


Most PowerShell cmdlets support a variety of parameters
Each parameter is designed to accept a very specific type

of input

Some parameters work with integers, others with text, etc.

Some commands require specifying parameter names at the


command line, while others are optional

Some parameters are optional, while others are mandatory

Always remember: Consult the cmdlets Get-Help for

information about each parameter

Get-Help will show which are optional, as well as what type of


input is expected

Positional Parameters
Positional parameters do not require specifying their name

at the command line

Their use is based on the position of the parameter in the


input

They are used to make typing easier, reduce input


Stop-Process id 53 #Executes correctly
Stop-Process 53 #Executes correctly

Positional parameters are displayed in square brackets in

the cmdlets help

Stop-Process [-Id] <Int32[]>


Parameter names, those which are specified at the

command line, can be used in any order

Using parameter names is useful for code clarity

Pipeline Input ByValue


Many parameters are designed to accept input from the

pipeline. This process is called binding.

You have already done this as you pipeline commands to each


other. The second command accepts the input of the first.

Get-Service | Where-Object { $_.Status eq "Running" }

Here, the Where-Object cmdlet uses a positional parameter


named InputObject to accept pipeline input ByValue.

-InputObject <psobject>
Specifies the objects to be filtered. You can
Required?
Position?
Default value
Accept pipeline input?
Accept wildcard characters?

false
named
true (ByValue)
False

Pipeline Input ByPropertyName


ByValue binding is easy: Acceptable values are enough to

validate incoming input.

Other parameters bind ByPropertyName, which requires a

matching property name. This can be more difficult.

As before, reference the cmdlets help for details

Consider the help content for Get-Service:


-ComputerName <string[]>
Gets the services running on the specified computers
Required?
Position?
Default value
Accept pipeline input?
Accept wildcard characters?

false
named
Localhost
true (ByPropertyName)
False

Renaming Properties
Sometimes you need to bind cmdlets, but those cmdlets

use different property names for the same data. What do


you do?

ByValue is easy. Values are enough.

ByPropertyName requires renaming the property.

Renaming properties uses Select-Object.

Select-Object
@{Label=NewName;Expression={$_.OldName}}
Get-ADComputer filter * | Select-Object
@{Label="ComputerName";Expression={$_.Name}}
Get-ADComputer filter * | Select-Object *,
@{Label="ComputerName";Expression={$_.Name}} |
Get-Service

Demonstration: Working with Pipeline Input


Use pipeline input parameter binding

Understanding Passthrough
Some action cmdlets accept pipeline input, but do not

provide output.

New-ADUser name JohnD samaccountname JohnD

# This command has no output. Results cant be piped to


other commands as is.
Cmdlets that provide no output by default require an extra

parameter (-passThru) to pass on its objects.

New-ADUser name JohnD samaccountname JohnD


passThru | Enable-ADAccount
#New-ADUser result is now piped to Enable-ADAccount
-passThru is used by many cmdlets. See help for details.

Demonstration: Using the Passthru Parameter


Use the passThru parameter of cmdlets that support it

Lab C: Using Pipeline Parameter Binding


Exercise 1: Using Advanced Pipeline Features

Exercise 2: Working with Multiple Computers


Exercise 3: Stopping a List of Processes
Exercise 4: Binding Properties to Parameters

Logon information
Virtual machine

LON-DC1

LON-SVR1

Logon user name

Contoso\Administrator Contoso\Administrator Contoso\Administrator

Password

Pa$$w0rd

Pa$$w0rd

Estimated time: 30 minutes

LON-SVR2

Pa$$w0rd

Lab Scenario
You are a system administrator for a company with about

100 users and desktop computers.

You want to perform a set of tasks against those users and

computers using Windows PowerShell. You want to


accomplish those tasks using data from external files.

You need to add a set of users to Active Directory, using

properly-formatted and improperly-formatted CSV files.

You also need to regularly reboot a set of computers based

on the contents of a CSV file.

Finally, you also need to stop a list of processes on

computers, based on the contents of a CSV file.

Lab Review
Do all cmdlets accept pipeline input like New-ADUser?
What is the advantage of a cmdlet parameter that accepts

pipeline input?

Before stopping a process, could a check be made to only

stop the process if it was using more than a certain


amount of physical or virtual memory?

Module Review and Takeaways


Where can the $_ placeholder be used?
What cmdlet do you use to remove selected objects from

the pipeline?

What kind of object is output by Select-Object when you

specify property names?

What kind of object is output by Measure-Object?

Class Discussion
Common issues related to core cmdlets
Best practices related to core cmdlets

You might also like