0% found this document useful (0 votes)
26 views24 pages

Introduction to PowerShell Basics

PowerShell is a command line shell and scripting language that can help automate tasks. It operates on objects rather than text and includes cmdlets that can be used to manage resources. The document provides an introduction to PowerShell and instructions for installing and verifying an installation.

Uploaded by

slgreen.bmaps
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views24 pages

Introduction to PowerShell Basics

PowerShell is a command line shell and scripting language that can help automate tasks. It operates on objects rather than text and includes cmdlets that can be used to manage resources. The document provides an introduction to PowerShell and instructions for installing and verifying an installation.

Uploaded by

slgreen.bmaps
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Introduction

PowerShell is a command-line shell and a scripting language all in one. It was designed
as a task engine that uses cmdlets to wrap tasks that people need to do. In PowerShell,
you can run commands on local or remote machines. You can do tasks like managing
users and automating workflows.

Whether you're part of an operations team or a development team that's adopting


DevOps principles, PowerShell can help. You can use it to address various tasks, such as
managing cloud resources and continuous integration and continuous delivery (CI/CD).
PowerShell offers many helpful commands, but you can expand its capabilities at any
time by installing modules.

When you install PowerShell, you can evaluate its features to see if it's a good fit for
your team.

Learning objectives
After completing this module, you'll be able to:

 Understand what PowerShell is and what you can use it for.


 Use PowerShell commands to automate tasks.

Prerequisites
 Basic familiarity with using a command-line shell like Command Prompt or Git
Bash.
 Visual Studio Code installed.
 Ability to install Visual Studio Code extensions.
 Ability to install software on your computer, if you're not using a Windows
operating system.
What is PowerShell?
PowerShell consists of two parts: a command-line shell and a scripting language. It
started out as a framework to automate administrative tasks in Windows. PowerShell has
grown into a cross-platform tool that's used for many kinds of tasks.

A command-line shell lacks a graphical interface, where you use a mouse to interact
with graphical elements. Instead, you type text commands into a computer console.
Here are some of the benefits of using a console:

 Interacting with a console is often faster than using a graphical interface.


 In a console, you can run batches of commands, so it's ideal for task automation
for continuous-integration pipelines.
 You can use a console to interact with cloud resources and other resources.
 You can store commands and scripts in a text file and use a source-control system.
This capability is probably one of the biggest benefits, because your commands
are repeatable and auditable. In many systems, especially government systems,
everything must be traced and evaluated, or audited. Audits cover everything from
database changes to changes done by a script.

Features
PowerShell shares some features with traditional shells:

 Built-in help system: Most shells have some kind of help system, in which you can
learn more about a command. For example, you can learn what the command
does and what parameters it supports. The help system in PowerShell provides
information about commands and also integrates with online help articles.
 Pipeline: Traditional shells use a pipeline to run many commands sequentially. The
output of one command is the input for the next command. PowerShell
implements this concept like traditional shells, but it differs because it operates on
objects over text. You learn more about this feature later in this module.
 Aliases: Aliases are alternate names that can be used to run commands.
PowerShell supports the use of common aliases such as cls (clear the screen)
and ls (list the files). Therefore, new users can use their knowledge of other
frameworks and don't necessarily have to remember the PowerShell name for
familiar commands.

PowerShell differs from a traditional command-line shell in a few ways:


 It operates on objects over text. In a command-line shell, you have to run scripts
whose output and input might differ, so you end up spending time formatting the
output and extracting the data you need. By contrast, in PowerShell you use
objects as input and output. That means you spend less time formatting and
extracting.
 It has cmdlets. Commands in PowerShell are called cmdlets
(pronounced commandlets). In PowerShell, cmdlets are built on a common runtime
rather than separate executables as they are in many other shell environments.
This characteristic provides a consistent experience in parameter parsing and
pipeline behavior. Cmdlets typically take object input and return objects. The core
cmdlets in PowerShell are built in .NET Core, and are open source. You can extend
PowerShell by using more cmdlets, scripts, and functions from the community and
other sources, or you can build your own cmdlets in .NET Core or PowerShell.
 It has many types of commands. Commands in PowerShell can be native
executables, cmdlets, functions, scripts, or aliases. Every command you run belongs
to one of these types. The words command and cmdlet are often used
interchangeably, because a cmdlet is a type of command.

Installation
In this module, you practice using PowerShell on your computer. PowerShell is available
across platforms. However, if you use a computer that runs Linux, macOS, or an older
version of Windows, you need to install it.

Instructions for installing PowerShell are different for each OS. Before you continue, take
a few minutes to install PowerShell or to verify your PowerShell installation. The next
unit in this module shows you how to verify your installation.

Windows

If you're running Windows 8 or later, a version of PowerShell called Windows


PowerShell should already be installed. This version differs slightly from the most up-to-
date PowerShell release, but it works fine for learning purposes.

You can open Windows PowerShell from the Start menu.

Other operating systems


If your computer runs something other than Windows 8 or later, you need to install
PowerShell. To find the installation instructions for your OS, see Install various versions
of PowerShell.

PowerShell extension for Visual Studio Code

We recommend that you use the PowerShell extension for Visual Studio Code to author
your PowerShell scripts and to run the commands in this module. This extension lets you
run commands, and also helps you with snippets, code completion, and syntax
highlighting.

Exercise - Run your first PowerShell


commands
Microsoft Learn needs your permission to create Azure resources.

For more information, please check the troubleshooting guidance page.

Review permissions

In this unit, you use Azure Cloud Shell as a Linux terminal. You also can access Cloud
Shell through the Azure portal or at Cloud Shell sign-in. You don't need to install
anything on your PC or laptop to use Cloud Shell.

Note

In this module, you're using the Azure Cloud Shell on the right-hand side of the screen,
but in real-world situations, you can also use the integrated Terminal in Visual Studio
Code by selecting Terminal > New Terminal, then selecting Powershell in the drop-
down in the top-left of the Terminal window.

Before beginning this exercise, be sure to activate the sandbox.

1. Run the following command in Cloud Shell, and then press Enter to verify that
your system is set up to use PowerShell. The $PSVersionTable verifies your
installation.

PowerShellCopy
$PSVersionTable
Your output resembles the following table:

OutputCopy
Name Value
---- -----
PSVersion 7.3.6
PSEdition Core
GitCommitId 7.3.6
OS Linux 5.4.0-1058-azure #60~18.04.1-Ubuntu SMP
Tue Aug 31 20:34:4…
Platform Unix
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion 2.3
SerializationVersion [Link]
WSManStackVersion 3.0

The output provides information about your PowerShell version, and your platform
and edition.

For information limited to your version of PowerShell, you can run a modified
version of $PSVersionTable.

2. Run the following command in Cloud Shell, and then press Enter.

PowerShellCopy
$[Link]

Your output now resembles the following table:

OutputCopy
Major Minor Patch PreReleaseLabel BuildLabel
----- ----- ----- --------------- ----------
7 3 6

This output gives you more details about your version of PowerShell.

Running $PSVersionTable results in output that looks like a table, but is actually an
object. For this reason, you can use a period ( .) to access a specific property, such
as PSVersion.

Locate commands
A cmdlet (pronounced "command-let") is a compiled command. A cmdlet can be
developed in .NET or .NET Core and invoked as a command within PowerShell.
Thousands of cmdlets are available in your PowerShell installation. The challenge lies in
discovering what the cmdlets are and what they can do for you.

Cmdlets are named according to a verb-noun naming standard. This pattern can help
you to understand what they do and how to search for them. It also helps cmdlet
developers create consistent names. You can see the list of approved verbs by using
the Get-Verb cmdlet. Verbs are organized according to activity type and function.

Here's a part of the output from running Get-Verb:

OutputCopy
Verb AliasPrefix Group Description
---- ----------- ----- -----------
Add a Common Adds a resource to a container, or atta…
Clear cl Common Removes all the resources from a contai…

This listing shows the verb and its description. Cmdlet developers should use an
approved verb, and also ensure that the verb description fits their cmdlet's function.

Three core cmdlets allow you to delve into what cmdlets exist and what they do:

 Get-Command: The Get-Command cmdlet lists all of the available cmdlets on your
system. Filter the list to quickly find the command you need.
 Get-Help: Run the Get-Help core cmdlet to invoke a built-in help system. You can
also run an alias help command to invoke Get-Help but improve the reading
experience by paginating the response.
 Get-Member: When you call a command, the response is an object that contains
many properties. Run the Get-Member core cmdlet to drill down into that response
and learn more about it.

Locate commands by using Get-Command


When you run the Get-Command cmdlet in Cloud Shell, you get a list of every command
that's installed in PowerShell. Because thousands of commands are installed, you need a
way to filter the response so you can quickly locate the command that you need.

To filter the list, keep in mind the verb-noun naming standard for cmdlets. For example,
in the Get-Random command, Get is the verb and Random is the noun. Use flags to target
either the verb or the noun in the command you want. The flag you specify expects a
value that's a string. You can add pattern-matching characters to that string to ensure
you express that, for example, a flag's value should start or end with a certain string.
These examples show how to use flags to filter a command list:

 -Noun: The -Noun flag targets the part of the command name that's related to the
noun. That is, it targets everything after the hyphen ( -). Here's a typical search for a
command name:

PowerShellCopy
Get-Command -Noun a-noun*

This command searches for all cmdlets whose noun part starts with a-noun.

 -Verb: The -Verb flag targets the part of the command name that's related to the
verb. You can combine the -Noun flag and the -Verb flag to create an even more
detailed search query and type. Here's an example:

PowerShellCopy
Get-Command -Verb Get -Noun a-noun*

Now you've narrowed the search to specify that the verb part needs to match Get,
and the noun part needs to match a-noun.

Exercise - Locate commands


Sandbox activated! Time remaining:

3 hr 7 min

You have used 1 of 10 sandboxes for today. More sandboxes will be available tomorrow.

In this unit, you use the Azure Cloud Shell on the right-hand side as your Linux terminal.
You can access Cloud Shell through the Azure portal or the Cloud Shell sign-in. You
don't have to install anything on your PC or laptop to use it.

Here, you run commands that help you learn more about PowerShell. PowerShell isn't
something you learn overnight; it's learned command by command. You can speed up
your learning by effectively using the core cmdlets.

Locate a command
Locate commands by running the Get-Command cmdlet. This cmdlet helps you search all
of the cmdlets installed on your system. Use flags to narrow down your search results to
just the cmdlets that fit your scenario.
In this scenario, you're looking for a cmdlet that can help you work with files.

1. Run the command Get-Command with the flag -Noun. Specify File* to find anything
related to files.

PowerShellCopy
Get-Command -Noun File*

The response shows something similar to the following text:

OutputCopy
CommandType Name Version
Source
----------- ---- -------
------
Cmdlet Get-FileHash [Link]
[Link]
Cmdlet Out-File [Link]
[Link]
Cmdlet Unblock-File [Link]
[Link]

The cmdlets Get-FileHash, Out-File, and Unblock-File all match your query. Now,
you have a manageable response. To further filter the response, add the -
Verb parameter to your query.

2. Run Get-Command. Specify the flags -Verb and -Noun.

PowerShellCopy
Get-Command -Verb Get -Noun File*

The result is similar to the following output:

OutputCopy
CommandType Name Version
Source
----------- ---- -------
------
Cmdlet Get-FileHash [Link]
[Link]

This time, only one record matches your search, because you specified both the -
Noun parameter and the -Verb parameter.
Because the domain you work in is file management, you specified File as the noun. If
you know what you want to do within that domain, you can specify -Verb parameters. By
using one or possibly two parameters, you can quickly find the cmdlet you need.

Summary
In this module, you started by learning what PowerShell is and what you can use it for.
You explored its primary features, and how it differs from traditional shells like Git Bash.
You also looked at how to install PowerShell, and briefly explored authoring it by using
Visual Studio Code and an extension.

You then learned about compiled commands called cmdlets. You looked specifically at a
command called Get-Command that helps you locate the command you need.

You should now have a good understanding of PowerShell, what it's used for, and how
to use its commands efficiently.

Introduction
PowerShell comes preinstalled with numerous commands. To use PowerShell
commands efficiently, you need to understand how they work. For example, you need to
know what parameters the commands take and that there might be more than one way
to call a command.

It's also helpful to know what a command returns, what type it returns, and the
command's properties. By knowing these things, you can configure how help is shown.
You also get a hint of how a specific command fits with another command if you
combine them.

Learning objectives
When you finish this module, you'll be able to:

 Inspect commands to understand how to call them.


 Understand what a command returns and customize what it returns.

Prerequisites
To complete this module, you should:

 Be able to start a terminal.


 Understand what PowerShell is.
 Know how to run a command in PowerShell.

Discover a command by using the help


system
By using the built-in help system in PowerShell, you can find out more about a specific
command. You use the Get-Command cmdlet to locate a command that you need. After
you've located the command, you might want to know more about what the command
does and various ways to call it.

Discover cmdlets by using the help system and Get-


Help
You can use the Get-Help core cmdlet to learn more about a command. Typically, you
invoke Get-Help by specifying it by name and adding the -Name flag that contains the
name of the cmdlet you want to learn about. Here's an example:

PowerShellCopy
Get-Help -Name Get-Help

Update help

New versions of PowerShell don't include the help system by default. The first time you
run Get-Help, you're asked to install the help files. You can also run the Update-
Help cmdlet to install the help files. Because a call to Update-Help downloads many help
files, the command can fetch only once per day by default. You can override this
fetching behavior by using the -Force flag.

You update the help files differently on Windows compared to Linux or macOS. The
process differs because when you run the Update-Help cmdlet, help files are fetched over
the internet by matching your computer's culture. On Windows, a culture is already
installed, but it's missing on Linux and macOS. So you need to specify a culture when
you update help files on Linux and macOS.

Here's an example command:

PowerShellCopy
Update-Help -UICulture en-US -Verbose

This command specifies the -UICulture flag. It gives it the value en-US, which fetches US
English help files. To update your help files on macOS or Linux, use a culture that
corresponds to your machine's culture.

Explore help sections

When you invoke Get-Help on a cmdlet, a help page is returned. The page includes many
sections. You'll likely see these common sections:

 NAME: Provides the name of the command.


 SYNTAX: Shows ways to call the command by using a combination of flags, and
sometimes, allowed parameters.
 ALIASES: Lists any aliases for a command. An alias is a different name for a
command, and it can be used to invoke the command.
 REMARKS: Provides information about what commands to run to get more help
for this command.
 PARAMETERS: Provides details about the parameter. It lists its type, a longer
description, and acceptable values, if applicable.

Filter the help response

If you don't want to display the full help page, narrow the response by adding flags to
your Get-Help command. Here are some flags you can use:

 Full: Returns a detailed help page. It specifies information like parameters, inputs,
and outputs that you don't get in the standard response.
 Detailed: Returns a response that looks like the standard response, but it includes
a section for parameters.
 Examples: Returns only examples, if any exist.
 Online: Opens a web page for your command.
 Parameter: Requires a parameter name as an argument. It lists a specific
parameter's properties.
For example, you can use the following command to return only the Examples section of
the help page.

PowerShellCopy
Get-Help Get-FileHash -Examples

Improve the reading experience

Running Get-Help returns the entire help page. The page might not provide the best
reading experience. You might have to scroll to find the section you want to read. A
better approach is to use the help alias. The help alias pipes Get-Help into a function that
ensures that your output is readable line by line. It also makes the response readable
page by page, by paginating the output. You'll use the help alias in the next unit.

Exercise - Using help


This module requires a sandbox to complete. You have used 1 of 10 sandboxes for
today. More sandboxes will be available tomorrow.

Activate sandbox

After you find a cmdlet you want to use, you can learn more about it. For example, you
can learn about the different ways to call it, what parameters you can use, and example
use cases.

Use Get-Help to discover commands


Use the Get-Help cmdlet to learn about cmdlets.

1. Run the command Get-Help:

PowerShellCopy
Get-Help -Name Get-FileHash

This command produces an output similar to the following text:

OutputCopy
NAME
Get-FileHash

SYNOPSIS
Computes the hash value for a file by using a specified hash algorithm.
SYNTAX
Get-FileHash [-InputStream] <[Link]> [[-Algorithm] {SHA1 | SHA256
| SHA384 | SHA512 | MD5}]
[<CommonParameters>]

Get-FileHash [-LiteralPath] <[Link][]> [[-Algorithm] {SHA1 | SHA256


| SHA384 | SHA512 | MD5}]
[<CommonParameters>]

Get-FileHash [-Path] <[Link][]> [[-Algorithm] {SHA1 | SHA256 |


SHA384 | SHA512 | MD5}]
[<CommonParameters>]

DESCRIPTION
The `Get-FileHash` cmdlet computes the hash value for a file by using a
specified hash algorithm. A hash value
is a unique value that corresponds to the content of the file. Rather than
identifying the contents of a file
by its file name, extension, or other designation, a hash assigns a unique
value to the contents of a file.
File names and extensions can be changed without altering the content of
the file, and without changing the
hash value. Similarly, the file's content can be changed without changing
the name or extension. However,
changing even a single character in the contents of a file changes the hash
value of the file.

The purpose of hash values is to provide a cryptographically-secure way to


verify that the contents of a file
have not been changed. While some hash algorithms, including MD5 and SHA1,
are no longer considered secure
against attack, the goal of a secure hash algorithm is to render it
impossible to change the contents of a file
-- either by accident, or by malicious or unauthorized attempt -- and
maintain the same hash value. You can
also use hash values to determine if two different files have exactly the
same content. If the hash values of
two files are identical, the contents of the files are also identical.

By default, the `Get-FileHash` cmdlet uses the SHA256 algorithm, although


any hash algorithm that is supported
by the target operating system can be used.

RELATED LINKS
Online Version:
[Link]
filehash?view=powe
rshell-7.2&WT.mc_id=ps-gethelp
Format-List

REMARKS
To see the examples, type: "Get-Help Get-FileHash -Examples"
For more information, type: "Get-Help Get-FileHash -Detailed"
For technical information, type: "Get-Help Get-FileHash -Full"
For online help, type: "Get-Help Get-FileHash -Online"

Because this output is difficult to read, you decide to use an alternative that is less
verbose. That is, you use the help alias.

2. Enter the help command:

PowerShellCopy
help Get-FileHash

Now, a reduced version of the help output is shown. It looks like the following text:

OutputCopy
NAME
Get-FileHash

SYNOPSIS
Computes the hash value for a file by using a specified hash algorithm.

SYNTAX
Get-FileHash [-InputStream] <[Link]> [[-Algorithm] {SHA1 | SHA256
| SHA384 | SHA512 | MD5}]
[<CommonParameters>]

Get-FileHash [-LiteralPath] <[Link][]> [[-Algorithm] {SHA1 | SHA256


| SHA384 | SHA512 | MD5}]
[<CommonParameters>]

Get-FileHash [-Path] <[Link][]> [[-Algorithm] {SHA1 | SHA256 |


SHA384 | SHA512 | MD5}]
[<CommonParameters>]

DESCRIPTION
The `Get-FileHash` cmdlet computes the hash value for a file by using a
specified hash algorithm. A hash value
is a unique value that corresponds to the content of the file. Rather than
identifying the contents of a file
by its file name, extension, or other designation, a hash assigns a unique
value to the contents of a file.
File names and extensions can be changed without altering the content of
the file, and without changing the
hash value. Similarly, the file's content can be changed without changing
the name or extension. However,
changing even a single character in the contents of a file changes the hash
value of the file.

The purpose of hash values is to provide a cryptographically-secure way to


verify that the contents of a file
have not been changed. While some hash algorithms, including MD5 and SHA1,
are no longer considered secure
against attack, the goal of a secure hash algorithm is to render it
impossible to change the contents of a file
-- either by accident, or by malicious or unauthorized attempt -- and
maintain the same hash value. You can
also use hash values to determine if two different files have exactly the
same content. If the hash values of
two files are identical, the contents of the files are also identical.

By default, the `Get-FileHash` cmdlet uses the SHA256 algorithm, although


any hash algorithm that is supported
by the target operating system can be used.

You can move through the results vertically, row by row, by using the arrow keys.
To view the results page by page, use the Spacebar.

3. Run help Get-FileHash -Examples:

PowerShellCopy
help Get-FileHash -Examples

The output looks like the following text:

OutputCopy
NAME
Get-FileHash

SYNOPSIS
Computes the hash value for a file by using a specified hash algorithm.

--------- Example 1: Compute the hash value for a file ---------

Get-FileHash /etc/apt/[Link] | Format-List

Algorithm : SHA256
Hash :
3CBCFDDEC145E3382D592266BE193E5BE53443138EE6AB6CA09FF20DF609E268
Path : /etc/apt/[Link]

------ Example 2: Compute the hash value for an ISO file ------

Get-FileHash C:\Users\user1\Downloads\Contoso8_1_ENT.iso -Algorithm SHA384


| Format-List

Algorithm : SHA384
Hash :
20AB1C2EE19FC96A7C66E33917D191A24E3CE9DAC99DB7C786ACCE31E559144FEAFC695C58E508E
2EBBC9D3C96F21FA3
Path : C:\Users\user1\Downloads\Contoso8_1_ENT.iso
This output contains a list of examples that use the cmdlet. Locate the part of the
response that contains the text Example 1. This portion of the text shows how you
can use Get-FileHash with a file path by piping it to the cmdlet Format-List.

Tip

To quickly see an example, add the flag -Examples when you search for help.

Discover objects
When a cmdlet runs, it returns an object. When you invoke a cmdlet, the response you
see has been formatted and might not necessarily represent all the available information
for the response. To know more about what's being returned and how you can modify
what is returned, you can use the command Get-Member.

Discover objects by using Get-Member


The Get-Member cmdlet is meant to be piped on top of the command you run so that you
can filter the output. A typical command-line invocation of Get-Member might look like
the following example:

PowerShellCopy
Get-Process -Name 'name-of-process' | Get-Member

This command first produces an object result by calling Get-Process. That result is
passed as an input to Get-Member by using the pipe (|). In return, you get a table result
that includes the Name, MemberType, and Definition columns. You also get the type of the
returned object.

Tip

To get a list of the processes running on your machine, run Get-Process.

Search by type

The first line of the response, running the Get-Member command, is the type of the
returned object. When you know the type, you can search for other cmdlets that operate
on the same type. Explore these related commands to quickly build your knowledge in
the domain you're working in.

Let's say you invoked the PowerShell command that lists all members for a specific
process. The first few rows of the result look something like this output:

OutputCopy
TypeName: [Link]

Name MemberType Definition


---- ---------- ----------
Handles AliasProperty Handles = Handlecount

The first row indicates that the type is [Link]. Use this type as a
search argument to look for other cmdlets that use this type. Here's an example
command:

PowerShellCopy
Get-Command -ParameterType Process

The result is a list of cmdlets that operate on this type. Little by little, you can learn more
about PowerShell by using Get-Member and by learning to interpret its result.

Tip

PowerShell is meant to be learned a little at a time. A great way to discover related


cmdlets is by using the returned type to search for cmdlets by type.

Filter a Get-Member result by using Select-Object

When you run Get-Member, the result is verbose. That is, many rows are returned. The
object might have properties, like events and methods. To make the answer less
verbose, you can filter on specific columns and also decide which columns to display.
Keep in mind that the returned answer is already a subset of all the columns in the
response.

Take a look at a Get-Member response that includes many columns. By introducing


the Select-Object cmdlet, you can choose which columns appear in the response. The
command expects either a comma-separated list of column names or a wildcard
character, such as an asterisk (*), which indicates all columns.
When you use the Select-Object command in the context of Select-Object Name,
MemberType, you specify only the columns you want. In this case, the columns
are Name and MemberType. The command line would look like this:

PowerShellCopy
Get-Process -Name 'name-of-process' | Get-Member | Select-Object Name, MemberType

This filtering pattern returns an output that includes fewer columns. Here's an example
of the result:

OutputCopy
Name MemberType
---- ----------
Handles AliasProperty

You also can filter the response by rows. For example, you can use the -MemberType
Method flag to specify that you're interested in the rows in which the member type is a
method. You might want to show only specific rows, for example, if you want to locate
and run a specific method.

Tip

It's generally better to use dedicated cmdlets than to run methods on an object.

Summary
In this module, you learned how to inspect a command that you intend to use. Looking
at a command before you use it helps you call the command correctly and learn the
different ways you can call the command.

You also looked at inspecting what a command returns. PowerShell commands return
objects. By calling Get-Member, you learn what type of object will be returned and the
object's properties. With that information, you can look for related commands that
operate on same object type.

You'll learn how to use object type information in later modules that look at pipelines
and combining multiple commands in a single command.

Resources
 Core cmdlets and using the help system
 Discovering objects

Introduction
In PowerShell, you run compiled commands, or cmdlets. By connecting these cmdlets,
you can create powerful combined statements, or pipelines. You'll find such combined
statements useful as you're looking to automate your workflows.

As part of creating these pipelines, it's beneficial to understand how to format the
output to your liking. For example, a carefully selected output format might allow you to
quickly get an overview of a situation, or make it easier to fit the output into a report.

When you learn to combine cmdlets, you unlock much of the power that's built into
PowerShell.

Learning objectives
After you complete this module, you'll be able to:

 Explore cmdlets further and construct a sequence of them in a pipeline.


 Apply sound principles to your commands by using filtering and formatting.

Selecting data
Running a command can be powerful, you get data from your local machine or from
across the network. To be even more effective, you need to learn how to get the data
that you want. Most commands operate on objects, as input or as output, or both.
Objects have properties and you may want to access a subset of those properties and
present them in a report. You might also want to sort the data based on one or more
properties. But how do you get there?

Use Get-Member to inspect output


When you pass the results of a command to Get-Member, Get-Member returns information
about an object, like:

 The type of object being passed to Get-Member.


 The Properties of the object that may be evaluated.
 The Methods of the object that may be executed.

Let's demonstrate this fact by running Get-Member on the command Get-Process.

PowerShellCopy
Get-Process | Get-Member

Note how you're using the pipe | and that by calling Get-Member, you are in fact creating
a pipeline already. The first few lines of output from the preceding statement look like
so:

OutputCopy
TypeName: [Link]

Name MemberType Definition


---- ---------- ----------
Handles AliasProperty Handles = Handlecount
Name AliasProperty Name = ProcessName
NPM AliasProperty NPM = NonpagedSystemMemorySize64
PM AliasProperty PM = PagedMemorySize64
SI AliasProperty SI = SessionId
VM AliasProperty VM = VirtualMemorySize64
WS AliasProperty WS = WorkingSet64
...

The output shows the type of object that the Get-Process command returns
([Link]). The rest of the response shows the name, type, and
definition of the object's members. You can see that If you want to fit Get-Process with
another command in a pipeline, pairing it with Get-Member is a good first step.

Select-Object
By default, when you run a command that is going to output to the screen, PowerShell
automatically adds the command Out-Default. When the output data is a collection of
objects, PowerShell looks at the object type to determine if there's a registered view for
that object type. If it finds one, it uses that view.

The view generally doesn't contain all the properties of an object because it wouldn't
display properly on screen, so only some of the most common properties are included
in the view.
You can override the default view by using Select-Object and choosing your own list of
properties. You can then send those properties to Format-Table or Format-List, to display
the table however you like.

Consider the result of running Get-Process on the process zsh:

OutputCopy
NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName
------ ----- ----- ------ -- -- -----------
0 0.00 0.01 0.38 644 620 zsh
0 0.00 0.01 0.38 727 727 zsh
0 0.00 0.01 0.38 731 731 zsh
0 0.00 0.01 0.38 743 743 zsh
0 0.00 0.01 0.38 750 750 zsh
0 0.00 0.88 0.91 15747 …47 zsh
0 0.00 0.01 0.29 41983 …83 zsh
0 0.00 1.16 0.31 68298 …98 zsh

What you see is a view that represents what you most likely want to see from this
command. However, this view doesn't show you a complete set of information. In order
to see something different, you can explicitly specify which properties you want to see in
the result.

Getting the full response

What you've seen so far is a limited response. To present the full response, you use a
wildcard *, like so:

PowerShellCopy
Get-Process zsh | Format-List -Property *

The * character shows you every attribute and its value, which allows you to investigate
the values you're interested in. The full response also uses presentation names for
properties instead of the actual property names, and presentation names look good in a
report.

Despite these benefits, you may not want a full output of data, but you may not be
content with the default response either.

Selecting specific columns


To limit the response and find a middle ground between the default response and the
full response, you want to select some properties you're interested in and have that as
parameter input to Select-Object. But, and here's a problem, you need to use the real
names for the columns. How do you find out the real names? Use Get-Member. A call
to Get-Member gives you all the properties and their actual names.

Finding the real property name

Let's quickly recap on the default response, with this subset:

OutputCopy
NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName
------ ----- ----- ------ -- -- -----------
0 0.00 0.01 0.38 644 620 zsh

From the default response, the properties Id and ProcessName are most likely called the
same, but CPU(s) is a presentation name, real property names tend to consist of only
text characters and no spaces. To find out the real name for a specific property, you can
use Get-Member:

PowerShellCopy
Get-Process zsh | Get-Member -Name C*

You now get a list of all members with names that start with a C. Among them is CPU,
which is likely what you want:

OutputCopy
TypeName: [Link]

Name MemberType Definition


---- ---------- ----------
CancelErrorRead Method void CancelErrorRead()
CancelOutputRead Method void CancelOutputRead()
Close Method void Close()
CloseMainWindow Method bool CloseMainWindow()
Container Property [Link] Container {get;}
CommandLine ScriptProperty [Link] CommandLine {get=…
Company ScriptProperty [Link] Company
{get=$[Link];}
CPU ScriptProperty [Link] CPU
{get=$[Link];}

You now know how to use Select-Object to ask for exactly what you need with the
correct property names, like so:
PowerShellCopy
Get-Process zsh | Select-Object -Property Id, Name, CPU

And here it is:

OutputCopy
Id Name CPU
-- ---- ---
644 zsh 0.3812141
727 zsh 0.3826498
731 zsh 0.3784953
743 zsh 0.3776352
750 zsh 0.3824036
15747 zsh 0.9097993
41983 zsh 0.2934763
68298 zsh 0.3121695

This sequence of commands gives you an output that differs from the default output
but contains properties that you care about.

Sorting
When you use Sort-Object in a pipeline, PowerShell sorts the output data by using the
default properties first. If no such properties exist, it then tries to compare the objects
themselves. The sorting is either by ascending or descending order.

By providing properties, you can choose to sort by specific columns, like so:

PowerShellCopy
Get-Process | Sort-Object -Descending -Property Name

In the preceding command, we're sorting by the column Name in descending order. To
sort by more than one column, separate the column names with a comma, like so:

PowerShellCopy
Get-Process | Sort-Object -Descending -Property Name, CPU

In addition to sorting by column name, you can also provide your own custom
expression. In this example, we use a custom expression to sort by the
columns Name and CPU and control the sort order for each column.

PowerShellCopy
Get-Process 'some process' | Sort-Object -Property @{Expression = "Name"; Descending
= $True}, @{Expression = "CPU"; Descending = $False}

The preceding example demonstrates how powerful and flexible Sort-Object can be.
This subject is a bit advanced and out of scope for this module, but is revisited in more
advanced modules.

You might also like