PowerShell Basics Textbook
PowerShell Basics Textbook
Textbook
Copyright © CYBERPRO Global | Confidential - Do not duplicate or distribute without written permission.
POWERSHELL BASICS
In this chapter, we will discuss the basics of PowerShell, including how to work with PowerShell
commands, how to use the PowerShell help system, how to use PowerShell commands to format
command’s output and how to save command’s output.
POWERSHELL CMDLETS
Most of the people when they first think of PowerShell, they usually think of the commands we can
execute and the information we get back from the OS. In the PowerShell environment, the
commands are called Cmdlets. A cmdlet performs an action and typically returns a .NET object. This
object can be further processed by concatenating several commands by using the pipeline. The
cmdlets in PowerShell have the same basic structure, as shown below.
Verb–Noun –Parameter1 –Parameter2 argument
The verb describes the action which is about to take place and the noun is the target of that action.
The parameter(s) is an optional characteristic of the noun, and some of the cmdlet's parameters
require an argument. There are a few common cmdlet verbs in PowerShell like Get, Set, Enable,
Disable, New and Remove. There are many other verbs like Start, Stop, Format, Invoke, and many
others, but they are less common. The following table summarizes the common verbs and their
meaning.
Verb Meaning
Get Queries a specific target
Set Modifies the setting of the target
Enable Enables settings on the target
Disable Disables settings on the target
New Creates a new instance of an object
Remove Removes an existing instance of an object
Copyright © CYBERPRO Global | Confidential - Do not duplicate or distribute without written permission.
For example, let’s take a look at the Get-Process cmdlet. As the name suggests, the Get-Process
command returns information about the running processes and has the following syntax:
Get-Process [[-Name] String[]] [-ComputerName String[]] [-
FileVersionInfo] [-Module] [CommonParameters]
Any parameter closed within a square bracket is an optional parameter, so there are no mandatory
parameters for the Get-Process command. You can see that the -Name and the -CompterName
parameters require an argument which is a type of string. The following example shows the output
of the Get-Process command when executed without any parameters.
PS C:\> Get-Process
Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName
------- ------ ----- ----- ------ -- -- -----------
201 15 2956 13960 9716 0 aesm_service
389 23 15800 30420 0.48 5752 1
ApplicationFrameHost
299 29 8572 28176 0.08 6264 1
backgroundTaskHost
360 20 7196 27424 0.25 13936 1
backgroundTaskHost
234 16 16484 34616 0.09 1744 1 chrome
218 15 12268 21532 0.06 2836 1 chrome
[…snip…]
Now say that you want to get information about a specific process, you can easily do so by adding
the -Name parameter followed by the name of the process.
PS C:\> Get-Process -Name notepad
Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName
------- ------ ----- ----- ------ -- -- -----------
224 12 2616 13188 0.13 4216 1 notepad
As I have mentioned before, the return object(s) can be further processed by other commands using
the pipeline. For example, if we want to stop the notepad process, we can send the returned
Notepad process object to the Stop-Process cmdlet through the pipeline, as shown in the following
example.
PS C:\> Get-Process -Id 4216 | Stop-Process
Copyright © CYBERPRO Global | Confidential - Do not duplicate or distribute without written permission.
+ FullyQualifiedErrorId : NoProcessFoundForGiv-
enId,Microsoft.PowerShell.Commands.GetProcessCommand
You are probably wondering how should I know about all of those commands when I first jump into
PowerShell? How did you know about the Get-Process and the Stop-Process commands? How did
you know which parameters to use? The typical answers to those questions will be “I don’t know,
someone has shown that to me” or “I read about that somewhere”. These are acceptable answers,
but there is a better and more convenient way to learn about PowerShell cmdlets. In the upcoming
sections, we will discuss the PowerShell help system, the Get-Help and the Get-Command that will
help you to start working with PowerShell cmdlets.
This topic is by far the most important topic in this section, especially if you are new to PowerShell.
The PowerShell help system is a collection of PowerShell Help files that contain almost everything
you want to know about PowerShell cmdlets and functions, PowerShell concepts, aliases, providers
and more.
The PowerShell Help files should contain all the information about a cmdlet or a function just like the
man pages in Linux. Moreover, for many different cmdlets, you will also find some usage examples.
In this section, you will learn how to use the Get-Help command to access the PowerShell help files
and how to find the information you are looking for, but you can also find the PowerShell Help files in
the online PowerShell documentation at the following link:
https://docs.microsoft.com/en-us/powershell/
GET-HELP
The Get-Help cmdlet used to access the PowerShell Help files from the PowerShell console. You can
use the Get-Help cmdlet to get information about cmdlets, functions, scripts, providers, aliases, and
PowerShell concepts in general. To get help about a PowerShell cmdlet, for example, you can
execute the Get-Help command followed by the name of the cmdlet. If you just supply the cmdlet as
an argument, you usually get the information about the command in one page. Try to execute the
following command in a PowerShell console and see how the information fits into one page.
PS C:\> Get-Help Get-Process
NAME
Get-Process
SYNOPSIS
Gets the processes that are running on the local computer or a remote
com-puter.
Copyright © CYBERPRO Global | Confidential - Do not duplicate or distribute without written permission.
SYNTAX
Get-Process [[-Name] <String[]>] [-ComputerName <String[]>] [-
FileVersionInfo] [-Module] [<CommonParameters>]
DESCRIPTION
The Get-Process cmdlet gets the processes on a local or remote
computer.
[…snip…]
You can also invoke the Get-Help cmdlet by using help which is an alias of the Get-Help cmdlet. To
see the same information in one page as shown in the last example you can also type the cmdlet
followed by -? (hyphen followed by a question mark). The Get-Help command has several useful
parameters that can help you to find the information you are looking for. The following table lists
some of those parameters and their meaning.
Parameter Meaning
-Detailed Shows detailed information, including all sections. Usually on
more than one page.
Let’s see how we can use those parameters to get help about the Get-Process cmdlet. First, you can
get the basic information about the cmdlet, including a synopsis, different syntaxes, description of
the cmdlet, related links, and remarks.
Copyright © CYBERPRO Global | Confidential - Do not duplicate or distribute without written permission.
To list all the supported parameters, use -Parameter * as shown in the following example.
PS C:\> Get-Help Get-Process -Parameter *
-ComputerName <String[]>
Specifies the computers for which this cmdlet gets active processes.
The de-fault is the local computer.
This parameter does not rely on Windows PowerShell remoting. You can
use the ComputerName parameter of this cmdlet even
if your computer is not configured to run remote commands.
Required? false
Position? named
Default value None
Accept pipeline input? True (ByPropertyName)
Accept wildcard characters? false
-FileVersionInfo [<SwitchParameter>]
Indicates that this cmdlet gets the file version information for the
program that runs in the process.
[…snip…]
To see some usage examples, use the -Examples parameter as shown below.
PS C:\> Get-Help Get-Process -Examples
NAME
Get-Process
SYNOPSIS
Gets the processes that are running on the local computer or a remote
computer.
PS C:\>Get-Process
This command gets a list of all active processes running on the local
computer. For a definition of each column, see the
"Additional Notes" section of the Help topic for Get-Help.
Example 2: Get all available data about one or more processes
Copyright © CYBERPRO Global | Confidential - Do not duplicate or distribute without written permission.
You can pipe the output to more just like in Linux.
PS C:\> Get-Help Get-Process -Parameter * | more
You can also use wildcards to search Help files about something. For example, if you want to see all
the Help files related to alias. You can do so as follows.
PS C:\> Get-Help *alias*
Name Category Module
Synopsis
---- -------- ------ ---
-----
Export-Alias Cmdlet Microsoft.PowerShell.U...
Exports information about currently defined aliases ...
Get-Alias Cmdlet Microsoft.PowerShell.U...
Gets the aliases for the current session.
Import-Alias Cmdlet Microsoft.PowerShell.U...
Imports an alias list from a file.
New-Alias Cmdlet Microsoft.PowerShell.U...
Creates a new alias.
Set-Alias Cmdlet Microsoft.PowerShell.U...
Creates or changes an alias for a cmdlet or other co...
You can update the PowerShell Help system by using the Update-Help cmdlet. The Update-Help
cmdlet downloads the newest Help files of PowerShell modules and installs them locally on your
computer. To update your PowerShell Help system, open a new PowerShell console with
administrative privileges and execute the Update-Help cmdlet.
GET-COMMAND
The Get-Command cmdlet gets all the installed command on the computer, including cmdlets,
functions, aliases, workflows and more. If you just type Get-Command in a PowerShell console, you
will get a massive list of different cmdlets, aliases etc. that are installed on your computer.
PS C:\> Get-Help *alias*
Name Category Module
Synopsis
---- -------- ------ ---
-----
Export-Alias Cmdlet Microsoft.PowerShell.U...
Exports information about currently defined aliases ...
Get-Alias Cmdlet Microsoft.PowerShell.U...
Gets the aliases for the current session.
Import-Alias Cmdlet Microsoft.PowerShell.U...
Imports an alias list from a file.
Copyright © CYBERPRO Global | Confidential - Do not duplicate or distribute without written permission.
New-Alias Cmdlet Microsoft.PowerShell.U...
Creates a new alias.
Set-Alias Cmdlet Microsoft.PowerShell.U...
Creates or changes an alias for a cmdlet or other co...
[…snip…]
To list all the installed cmdlets, you need to add the -CommandType parameter and cmdlet as an
argument, as shown below.
PS C:\> Get-Command -CommandType cmdlet | more
CommandType Name
Version Source
----------- ---- ------
- ------
Cmdlet Add-AppvClientConnectionGroup
1.0.0.0 AppvClient
Cmdlet Add-AppvClientPackage
1.0.0.0 AppvClient
Cmdlet Add-AppvPublishingServer
1.0.0.0 AppvClient
Cmdlet Add-AppxPackage
2.0.1.0 Appx
[…snip…]
To list all the cmdlets related to something, you can add the -Name and use wildcards. For example,
the following command lists all the cmdlets contain the word “process” in their names.
PS C:\> Get-Command -CommandType cmdlet -Name *process*
CommandType Name
Version Source
----------- ---- ------
- ------
Cmdlet ConvertTo-ProcessMitigationPolicy 1.0.11
ProcessMitigations
Cmdlet Debug-Process
3.1.0.0 Microsoft.PowerShell.Management
Cmdlet Enter-PSHostProcess
3.0.0.0 Microsoft.PowerShell.Core
Cmdlet Exit-PSHostProcess
3.0.0.0 Microsoft.PowerShell.Core
Cmdlet Get-Process
3.1.0.0 Microsoft.PowerShell.Management
[…snip…]
Copyright © CYBERPRO Global | Confidential - Do not duplicate or distribute without written permission.
WORKING WITH FILES AND FOLDERS
In this section, you will be introduced with new cmdlets that will help you work with files and folders.
I want to include this section because I want to make you feel more comfortable with the PowerShell
console. You can change directory using the cd command just like in CMD, but the cd command in
PowerShell is an alias for the Set-Location cmdlet. You can use both, but cd is shorter.
PS C:\> Set-Location D:
PS D:\> cd C:
The New-Item cmdlet creates a new item and sets its value. The items that can be created depending
on the location or the component, for example, in the file system, the New-Item creates files or
folders, and in the Windows registry, it creates registry keys and entries. To define the type of the
new item, use the -Type parameter followed by the type of the item, as shown in the following
examples.
PS C:\> New-Item -Type directory demo
Directory: C:\
Directory: C:\demo
In the last example, first, we created a new folder named demo under C: and then we created an
empty txt file named info.txt under the demo folder. To list the content of a directory, you can use
the Get-ChildItem cmdlet or dir which is an alias for the Get-ChildItem cmdlet.
PS C:\> Get-ChildItem demo
Directory: C:\demo
Copyright © CYBERPRO Global | Confidential - Do not duplicate or distribute without written permission.
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 6/23/2020 6:04 PM 0 info.txt
PS C:\> dir demo
Directory: C:\demo
To remove (delete) file, use the Remove-Item cmdlet followed by a full path or the file name if the
file exists under your current working directory.
PS C:\> Remove-Item .\demo\info.txt
PS C:\>
To remove (delete) a folder and its content, use the Remove-Item cmdlet with the -Recurse -Force
parameters as shown below.
PS C:\> Remove-Item -Recurse -Force .\demo
There are several ways to add content to a file from the PowerShell console. You can use the echo
command and redirect the output to a file like in CMD, or you can use the Add-Content cmdlet. You
can also use the Net-Item cmdlet to create a new file and add to it some content as follows.
PS C:\> Get-Content .\demo\info.txt
First line.
Copyright © CYBERPRO Global | Confidential - Do not duplicate or distribute without written permission.
PS C:\> Get-Content .\demo\info.txt
First line.
Second line.
Third line.
OUTPUT FORMATS
PowerShell cmdlets produced some output that by default is returned to the console, but sometimes
you want to change the default format because the output mass your console or you just want to see
the information in a different format. There are four cmdlets in PowerShell that allow you to control
how the returned properties of an object are displayed. We have not discussed the object's
properties and methods yet, but we will cover that in the next chapter. The following table lists the
four cmdlets used for formatting, including a short description.
Verb Meaning
Format-Wide Displays the returned objects as a wide table with only one
property (default property) of each object.
Copyright © CYBERPRO Global | Confidential - Do not duplicate or distribute without written permission.
FORMAT-WIDE
The Format-Wide cmdlet displays only the default of property of the return object(s). Let’s pipe the
output of the Get-Process cmdlet into Format-Wide and see how the output looks like.
PS C:\> Get-Process | Format-Wide
aesm_service
ApplicationFrameHost
audiodg chrome
chrome chrome
chrome chrome
chrome chrome
chrome chrome
chrome conhost
conhost csrss
csrss ctfmon
DAX3API DAX3API
DbxSvc dllhost
dllhost
DolbyDAX2API
Dropbox Dropbox
Dropbox
DropboxUpdate
dwm EasyResume
[…snip…]
As you can see in the output above, the Format-Wide cmdlet returned only the name of the running
process on my computer. By default, the output is displayed in two columns by you can change the
number of columns with the -Column parameter as shown in the following examples.
PS C:\> Get-Process | Format-Wide -Column 1
aesm_service
ApplicationFrameHost
chrome
chrome
chrome
chrome
chrome
[…snip…]
Copyright © CYBERPRO Global | Confidential - Do not duplicate or distribute without written permission.
FORMAT-LIST
The Format-List cmdlet displays the returned objects as a list where each object's properties is
displayed on a new line, as shown below.
PS C:\> Get-Process | Format-List
Id : 9716
Handles : 201
CPU :
SI : 0
Name : aesm_service
Id : 2468
Handles : 476
CPU : 0.703125
SI : 2
Name : ApplicationFrameHost
Id : 2944
Handles : 485
CPU : 7.34375
SI : 0
Name : audiodg
[…snip…]
You can select the displayed properties of the returned objects by using the -Property parameter as
follows.
PS C:\> Get-Process -Name notepad | Format-List -Property name,id
Name : notepad
Id : 16732
You can use wildcard (*) to get all the properties of the returned object.
PS C:\> Get-Process -Name notepad | Format-List -Property *
Name : notepad
Id : 16732
PriorityClass : Normal
FileVersion : 10.0.18362.1 (WinBuild.160101.0800)
HandleCount : 230
WorkingSet : 13496320
PagedMemorySize : 2916352
PrivateMemorySize : 2916352
VirtualMemorySize : 156995584
[…snip…]
Copyright © CYBERPRO Global | Confidential - Do not duplicate or distribute without written permission.
FORMAT-TABLE
The Format-Table cmdlet displays the properties of the returned object(s) in a tabular layout where
each object's property is presented in a column. The Format-Table cmdlet allows you to select which
properties to display, as shown in the following examples.
PS C:\> Get-Process -Name notepad
Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName
------- ------ ----- ----- ------ -- -- -----------
224 12 2580 13244 0.16 16732 2 notepad
Name Id Path
---- -- ----
notepad 16732 C:\Windows\system32\notepad.exe
Notice how we customized the output and now it shows only the Name, Id, and the Path properties.
In the next chapter, you will learn about the Get-Member cmdlet that helps you find the properties
and methods that are supported by an object.
OUT-FILE
The cmdlets we have covered so far in this section, send their output (stdout) to the console, but if
you want to save the output in a file, you have to use the Out-File cmdlet. The Out-File cmdlet works
similarly to tee in Linux. You can overwrite the content of a file if the file exists or you can append
data if you don’t want to overwrite the file. The cmdlet also supports encoding so you can select the
encoding type.
To write the output of a cmdlet into a file, simply pipe the output of the last command in the chain
into Out-File. You need to specify the file name or the path as an argument, as shown in the example
below.
PS C:\> Get-Process -Name notepad | Format-Table name,id,path | Out-File
C:\Temp\proc-info.txt
Copyright © CYBERPRO Global | Confidential - Do not duplicate or distribute without written permission.
You can append content to a file with the -Append parameter (if the file doesn’t exist, the command
creates a new file).
PS C:\> Get-Process -Name Calculator | Format-Table -Property
name,id,path | Out-File -Append C:\Temp\proc-info.txt
Name Id Path
---- -- ----
notepad 16732 C:\Windows\system32\notepad.exe
Name Id Path
---- -- ----
Calculator 8572 C:\Program
Files\WindowsApps\Microsoft.WindowsCalculator_10.1910.0.0_x64__8wekyb3d8b
bwe\Calculator.exe
Copyright © CYBERPRO Global | Confidential - Do not duplicate or distribute without written permission.
Copyright © CYBERPRO Global | Confidential - Do not duplicate or distribute without written permission.