Introduction to PowerShell Basics
Introduction to PowerShell Basics
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.
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:
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:
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.
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
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.
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.
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]
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.
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.
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.
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*
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.
PowerShellCopy
Get-Command -Verb Get -Noun File*
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:
Prerequisites
To complete this module, you should:
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.
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.
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:
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
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.
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.
PowerShellCopy
Get-Help -Name Get-FileHash
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>]
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.
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.
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>]
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.
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.
PowerShellCopy
help Get-FileHash -Examples
OutputCopy
NAME
Get-FileHash
SYNOPSIS
Computes the hash value for a file by using a specified hash algorithm.
Algorithm : SHA256
Hash :
3CBCFDDEC145E3382D592266BE193E5BE53443138EE6AB6CA09FF20DF609E268
Path : /etc/apt/[Link]
------ Example 2: Compute the hash value for an ISO file ------
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.
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
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]
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
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.
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:
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?
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]
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.
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.
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.
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]
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
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.