0% found this document useful (0 votes)
123 views115 pages

PowerShell 7 Fundamentals by Jeff Hicks

Uploaded by

Sanja Smoljanic
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)
123 views115 pages

PowerShell 7 Fundamentals by Jeff Hicks

Uploaded by

Sanja Smoljanic
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
You are on page 1/ 115

PowerShell 7 Fundamentals

Jeff Hicks
Notes by Zlatan Petrovic
2023-2024, Zürich
~ Table of contents ~

1. Installing and running PowerShell...........................................................................................................5


Course overview......................................................................................................................................5
Understanding the role of PowerShell.....................................................................................................5
A brief history of PS........................................................................................................................6
Why PowerShell matters?...............................................................................................................8
Power shell is a good language to start with...................................................................................8
PowerShell is the language of the cloud and the modern datacenter.............................................8
Jeff’s modern Management Paradigm............................................................................................9
PowerShell Yesterday, Today and Tomorrow...................................................................................9
Installing PowerShell..............................................................................................................................10
Requirements...............................................................................................................................10
Release Channels and Updates.....................................................................................................11
Installing PowerShell from the Powershell itself...........................................................................12
Running PowerShell...............................................................................................................................13
Discovering PowerShell..........................................................................................................................14
List all Parameters for a Cmdlet in Powershell.......................................................................................17
Command conventions.................................................................................................................18
Using Get-Command.....................................................................................................................19
2. Getting help with PowerShell................................................................................................................20
Course Overview....................................................................................................................................20
Getting PowerShell Help........................................................................................................................20
Version Check...............................................................................................................................20
The PowerShell way......................................................................................................................21
PowerShell Help Fundamentals....................................................................................................21
Update help..................................................................................................................................22
Interpreting PowerShell Help.................................................................................................................24
Understanding Help...............................................................................................................................26
Online PowerShell Help.........................................................................................................................26
3. Putting PowerShell to work....................................................................................................................27
Course Overview....................................................................................................................................27
Running PowerShell Commands............................................................................................................28
Understanding the PS Host...........................................................................................................32
Using Objects in the Pipeline.................................................................................................................33
Working with Objects in the Pipeline.....................................................................................................35
Sorting and Grouping....................................................................................................................35
Selecting and Measuring Object...................................................................................................36
Group Object................................................................................................................................36
Sort Object....................................................................................................................................37
Measure-Object............................................................................................................................37
Working with Objects Individualy.................................................................................................38
Filtering with PowerShell.......................................................................................................................41
4. Leveraging PowerShell Providers and PSDrives......................................................................................45
Course Overview....................................................................................................................................45
Understanding PowerShell Provider and PSDrives.................................................................................46
Introduction to PS Providers.........................................................................................................46
PS Drives.......................................................................................................................................47
Registry Drive................................................................................................................................48
Function Provider.........................................................................................................................49
Variable Provider..........................................................................................................................49
Certificate Provider.......................................................................................................................50
WSMan management Provider.....................................................................................................50
Exploring PSDrive Operations................................................................................................................52
Essential Commands to manage PS Drives...................................................................................54
Creating the temporary and persistant PS Drive...........................................................................55
Creating a Drive in Registry Provider............................................................................................56
Creating a Drive in Certificate Provider.........................................................................................56
Module Summary.........................................................................................................................56
Working with Registry and Certificates with PSDrive.............................................................................57
Module Introduction....................................................................................................................57
Enumerating and Navigating Registry Keys and Values.................................................................57
Get-ItemProperty on regkeys to get the values............................................................................58
Example from local network on KiwiPC to query the remote registry..........................................58
Creating and Modifying Keys and Values......................................................................................59
Rename-Item to rename the key\Property............................................................................................60
Clearing and Deleting Registry Keys and Values............................................................................60
Working with Certificate Provider.................................................................................................60
Exploring Environment Variables..................................................................................................62
5. Learning the PowerShell Language........................................................................................................63
Course Overview....................................................................................................................................63
Using PowerShell Variables....................................................................................................................64
Variable Basics..............................................................................................................................64
Variable – Dynamic VS constant VS read-only...............................................................................67
Variable expansion........................................................................................................................68
Using Sub-expression to expand the variables in the quotes........................................................69
Advanced Options.........................................................................................................................70
Using common PowerShell Operators...................................................................................................74
Course intro..................................................................................................................................74
Using Arrays and Hashtables..................................................................................................................87
Using Arrays and Hashtables.........................................................................................................87
Using PowerShell ScriptBlocks...............................................................................................................96
Working with Objects in PowerShell....................................................................................................101
Object Fundamentals..................................................................................................................101
Strings, Dates and Numbers................................................................................................................108
1. Installing and running PowerShell
Course overview

Understanding the role of PowerShell


Year 2005 PS was born.
- Code name was Monad
- Bulit on the .NET Framework
- Object-centered
- Interactive management via console
- Easy to learn scripting language
A brief history of PS

The PowerShell Paradigm

The PowerShell Paradigm


- No text parsing
- Manipulate objects
- In a pipeline (objects move trought the pipeline)
- If you can type it at the prompt, you can also script it
Example of previous VBScript code
PowerShell is a management engine who can be exposed interactively or by scripting.

Why PowerShell matters?

- Manage anything from anywhere from any platform


- Manage local systems and services
- Manage the cloud
- Do it for 1 or 100 or 1000
- Manage it interactive or Script
Power shell is a good language to start with
- PowerShell is a preferred automation language
- Scripting provides consistency
- Scripting provides documentation (srcipt itself is a documentation)
- Scripting provides efficiency

PowerShell is the language of the cloud and the modern datacenter.


Jeff’s modern Management Paradigm
- Learn the manual process (help you learning with the underlaying technology)
- Understand the technology
- Use powershell tools for on premise and also for Azure
- Automate!

Learn and leverage one tool


- Powershell is an enabling tool
- Scripts and Modules
- Workflows
- Desired state Configuration
- Just enough Administration

PowerShell Yesterday, Today and Tomorrow


Installing PowerShell

Requirements
Release Channels and Updates

LTS (Long terms Service Branch)


PoperShell 7 tied to LTS release of .NET Core
Stable
Current PowerShell 7.x release
Preview
In development

Update Notifications
PowerShell will check for updates every 24h. It will not be installed but you can get notification about
the update.
Installing PowerShell from the Powershell itself

From the PS itself is a bit of a husle to install new version of the PS.
But you can use the trick and get it trough winget

Note!
If you just search for “PowerShell” result will be to much.

To install it use and match the name on the ID instead of on Name object
Running PowerShell

Powershell is a engine behing the powershell application.

Hosting options are between classic CMD console and newer Windows terminal

User can start PS as regular or Administrator user


Note!
It is advisible to change the color of the console at least at uper part of the window to indicate in which
of the current session you are in (altough it is written “Administrator” in the upper console part :D.
Discovering PowerShell

What can I do in PowerShell?


How can I discover what I can do?
What is a PowerShell command?

Cmdlt is a PS’s core unit of execution which does only one thing with options like Get and Set. Cmdlt is
already compiled so you don’t see the code of it.
Functions are often like a cmdlet.

Scripts

Alias
Parameter are not the same as the switch as the called them as in PS switch is somothing else (flow
control).

Note!
If you want to search for all parameters of the Cmdlt you can use following technique
List all Parameters for a Cmdlet in Powershell
March 10, 2020 by Morgan
When you start work with a new Powershell cmdlet, you might want to get a list of
all the available parameters in the powershell cmdlet. We can use the
command GET-Command to display all the parameters.
(GET-Command GET-Process).parameters

We can also use the command Get-Help to display all the available
parameters with details.

Get-Help GET-Process -Parameter *

If you want to view only required or mandatory parameters in a cmdlet, we


can filter the results using Where-Object with Required property.:

Get-Help GET-Process -Parameter * | Where-Object {$_.Required -eq $true}


Command conventions

Note!
Use get-verb g* as an example to se the source\group of the command
Using Get-Command

Note!
If you press Ctrl+R in the console it will give you search for history
2. Getting help with PowerShell
Course Overview

Getting PowerShell Help

Version Check
The PowerShell way

PowerShell Help Fundamentals


Update help

Run command
Update-Help
Save-Help into a file and be aware of Version changes in help files
Interpreting PowerShell Help
Examples of Get-Help usage

Get-Help -Name Get-Command -Full


Get-Help -Name Get-Command -Detailed
Get-Help -Name Get-Command -Examples
Get-Help -Name Get-Command -Online
Get-Help -Name Get-Command -Parameter Noun
Get-Help -Name Get-Command -ShowWindow
! How to get all parameters trough get-command as a overview

PS C:\Users\Arioh> gcm Get-EventLog -Syntax


Get-EventLog [-LogName] <string> [[-InstanceId] <long[]>] [-ComputerName <string[]>] [-Newest <int>] [-
After <datetime>] [-Before <datetime>] [-UserName <string[]>] [-Index <int[]>] [-EntryType <string[]>] [-
Source <string[]>] [-Message <string>] [-AsBaseObject] [<CommonParameters>]

Get-EventLog [-ComputerName <string[]>] [-List] [-AsString] [<CommonParameters>]

Understanding Help

Online PowerShell Help


3. Putting PowerShell to work
Course Overview
Running PowerShell Commands

Discovering PS Commands

Command Types
Command Naming Conventions

Command Aliases
Note!
Get and invoke history

CommandType Name Version Source


----------- ---- ------- ------
Alias h -> Get-History

CommandType Name Version Source


----------- ---- ------- ------
Alias r -> Invoke-History

Set the Psreadline intelisense\ autocomplete option

Note!
Get+Psreadlineoption

If this is not working for you (for whatever reason) you can switch it off using this command:

Set-PSReadLineOption -PredictionSource None

I for one welcome our intelligent command line suggestions and would advise switching it on!

Set-PSReadLineOption -PredictionSource History


For those hardcore command line fans this predictor feature has a plugin model that allows you
create your own command-line predictors.
Understanding the PS Host

Different cmdlt’s send different objects to PS host. Write-host doesn’t send an object but rather just
write to host.
Using Objects in the Pipeline

Powershell is an interactive management tool that takes advantage of the pipeline.


Note!
Powershell create and consume objects.

What is an Object?
Working with Objects in the Pipeline

Note!
Everytinng is an Object! One command to measure all the objects!

Sorting and Grouping


Selecting and Measuring Object

Selecting the object as a common technique of filtering properties that you can discover with Get-
Member command, will create a new object in the pipeline.

Group Object
Sort Object

Sorting is on the level under the Names of members and depends on that values. Example for this is
members of get-service

You can use .NET to enumerate those members

You can also sort on multyple properties

Measure-Object

Note!
Get all the winevent with measures
Working with Objects Individualy

When you need to process objects one by one (individually) you can use ForEach-Object
In PS 7 is possible to run parallel process the objects in the Pipeline.

Note!
Do not mix ForEeach-Object which have “foreach’ alias with “foreach” keyword.

Demo ForEach-Object
ForEach-Object can use also alias “%”

Foreach-Object applied on methods on files operation

Let’s first create two files and then invoke .encrypt method on both of them trough ForEach-Object
Filtering with PowerShell

Filtering is very important step in everyday PS.

Filtering philosophies are Early and Late Filtering.


One of the ways to early filter is using the parameters of cmdlt itself.

Filtering with Where-Object is considered as late filtering


Traditional filtering syntax

Note!
Simplyfied syntax for Where-Object calling the object Name

Alternate modern syntax with $psitem

You will use in daily PS both filtering depending on the results you want and situation you are in.
Note!
Examples of bad code

Note!
Filtering in commands often is based on other tehnologies (AD filtering, etc…)
4. Leveraging PowerShell Providers and PSDrives
Course Overview
Understanding PowerShell Provider and PSDrives

Introduction to PS Providers
PS Drives
Registry Drive

Note!
Use Get-item and Get-ChildItem for retrieving and editing objects in these locations.
Function Provider

Variable Provider
Certificate Provider

WSMan management Provider


Exploring PSDrive Operations

Module introduction

Custom PS Drives Overview


Essential Commands to manage PS Drives

All *-Item as also *-ChildItem and *-ItemProperty commands are used to retrieve data and values in
operations on PS Drives.
Creating the temporary and persistant PS Drive
Creating a Drive in Registry Provider

Creating a Drive in Certificate Provider

Module Summary
Working with Registry and Certificates with PSDrive
Module Introduction

Enumerating and Navigating Registry Keys and Values


Get-ItemProperty on regkeys to get the values

Example from local network on KiwiPC to query the remote registry


Creating and Modifying Keys and Values

New-Item command to create registry entry


Rename-Item to rename the key\Property

Clearing and Deleting Registry Keys and Values

Retrieve the data from the registry key

To remove and delete the value run Remove-ItemProperety

To delete the reg key, you need first to clear the data from the key

Then use Remove-Item

Working with Certificate Provider

Navigate to Certificate location and notice that there are two certificate stores:
- CurrentUser
- LocalMachine

Note!
Check for all Certificates that will expire in 30 days

Exploring Environment Variables


5. Learning the PowerShell Language
Course Overview
Using PowerShell Variables

Variable Basics

What is a Variable?
Note!
Don’t assume that Variable will be updated if the source is updated! Test everything!

Note!
To get the values of the variable use Get-Variable | select *
Variable – Dynamic VS constant VS read-only

You can use -Force Parameter to overwrite these Variables but this will not work with “Constants”
Note!
-Passtrough parameter will passtrough objects that don’t have pipeline output
-NoElement Parameter will help with display of the objects in console

Variable expansion

Double VS single qoutes


Variables are expanded only in double quotes! Single quotes treat variables as text
Using the sub-expression to expand the variables

Using Sub-expression to expand the variables in the quotes


Advanced Options

Tee-Object
-Outvariable common parameter
You can save segments or chunks of date and you can even append to this date
Append the new data to the existing variable by adding it

Get-Service c* -outvariable +b

-PipelineVariable
Using common PowerShell Operators

Course intro
Operators are used to perform specific mathematical or logical functions on data, often stored in
variables. PowerShell offers multiple types of operators to manipulate data including:

 Arithmetic Operators
 Assignment Operators
 Unary Operators
 Equality Comparison Operators
 Logical Operators

Arithmetic Operators
PowerShell arithmetic operators are used to calculate numeric values. These include:

Operato
Name Description
r
+ Addition Adds numbers, concatenates strings and arrays.
- Subtraction Subtracts or negates numbers.
Multiplies numbers or copies strings and arrays a specified number of
* Multiplication
times.
/ Division Divides numbers.
% Modulo Returns the remainder of a division operation.
Arithmetic operators are binary operators, which means they act on two operands. Their syntax
in PowerShell is <Operand_1> <Arithmetic Operator> <Operand_2>.

$x = 5 + 5
# x is now 10

$x = $x - 8
# x is now 2

$x = $x * 3
# x is now 6

$x = $x / 2
# x is now 3

$x = $x % 2
# x is now 1
Arithmetic operators, + and *, also work on strings and arrays.

PS > $best_learning_platform = "Code" + "cademy"


PS > $best_learning_platform + "!" * 3
Codecademy!!!

PS > $fibonacci_1 = 0, 1, 1
PS > $fibonacci_2 = 2, 3, 5
PS > $fibonacci_1 + $fibonacci_2
0
1
1
2
3
5

PS > $fibonacci_2 * 2
2
3
5
2
3
5

Assignment Operators
Assignment operators can be used to assign, change, or append values to variables. These
operators are a shorter syntax for assigning the result of an arithmetic operator. The general
syntax of the assignment operators is: <Variable> <Assignment Operator> <Value>.

Operator Name Description


= Assignment $x = 3 assigns value 3 to variable x.
+= Addition Compound Assignment $x += 3 is short for $x = $x + 3.
-= Subtraction Compound Assignment $x -= 3 is short for $x = $x - 3.
*= Multiplication Compound Assignment $x *= 3 is short for $x = $x * 3.
/= Division Compound Assignment $x /= 3 is short for $x = $x / 3.
%= Modulo Compound Assignment $x %= 3 is short for $x = $x % 3.
Example
PS > $number = 4
PS > $number += 6 # $number is now 10
PS > $number /= 2 # $number is now 5
PS > $number
5

Unary Operators
Unary operators increase or decrease the value of a variable by 1.

Operator Name Description


++ Increment $x++ is short for $x = $x + 1.
-- Decrement $x-- is short for $x = $x - 1.
Equality Comparison Operators
Equality operators in PowerShell are binary operators that compare two integer or string values
that return True if the operator condition is met, otherwise False.

Operator Name Description


-eq Equal $x -eq $y is True if x and y are equal.
-ne Not Equal $x -ne $y is True if x and y are not equal.
-gt Greater Than $x -gt $y is True if x is greater than y.
-lt Less Than $x -lt $y is True if x is less than y.
-ge Greater Than or Equal to $x -ge $y is True if x is greater than or equal to y.
-le Less Than or Equal to $x -le $y is True if x is less than or equal to y.

Logical Operators
Logical operators allow us to combine multiple operator expressions and statements into
complex conditionals. They operate on boolean values and return boolean values.

Operator Name Description


-and And $x -and $y is True only if $x and $y are both True.
-or Or $x -or $y is True if either $x or $y is True.
-xor Xor $x -xor $y is True if only, but not both, $x or $y is True.
! or -not Not !$x is True when $x is False and False when $x is True.

Operator Precedence
Precedence order is the order in which PowerShell evaluates the operators if multiple operators
are used in the same expression. Operator precedence in PowerShell is as follows:

1. Parentheses: ( )
2. Unary operators: ++, --
3. !, not
4. Arithmetic operators: *, /, %, +, -
5. Comparison operators: -eq, -ne, -gt, -ge, -lt, -le
6. -and, -or, -xor
7. Assignment operators: =, +=, -=, *=, /=, %=

Examples
PS > $num_1 = 4
PS > $num_2 = 3
PS > $num_1 -lt $num_2 # num_1 is not less than num_2
False

PS > $num_2++ # num_2 is now 4


PS > $num_1 -ge $num_2 # num_1 is greater than or equal to num_2
True

PS > $num_1 /= 2 # num_1 is now 2


PS > $num_1 -lt $num_2 -xor $num_1 -ge $num_2 # True because only one expression
is True
True

Comparison Operators
Match and Notmatch Operator
Math and Range Operators

Use parenthesis to control precedence in more complex operations.

Range operator
Logical Operators

Note!
Parentheses are not mandatory but helpful.
Also used to confirm (true\false) scenario or use reverse boolean
Chain operators (PS 7)

Chain operators or you can use if-else statement.


Ternary Operator

Null Operators
Type operators

Special operators
Using Arrays and Hashtables

Using Arrays and Hashtables

Array (collections) fundamentals


To access the indivudual elements in the array, choose the right index number. You can also use inderx
range as shown in the last command.

!Note
Example of test-coonection with array filling for succes ping\test-connection

You can have different types of objects in array and get-member will show them all
Note!
Using -contain and -notcontain to check the arrays

Splitting and Joining

You can split string, split on delimiter as also choose the how much elements you want to split in the
variable. You can only split on single delimiter. To use more use -split operator.

Note!
help about_Split

Join

Join is rare case where you can use operator on the first place and it will work
Doing more with arrays

Note!
Technicaly you can’t remove element from the array but you can rebuild it

Hashtable Fundamentals
Example of work with hashtable

Use of Quotes for key\values that have space in the name.

Hashtable is a special type of object

To add the key\pair use .Add method

If you try to play stupid, you can test the ++ operator on string 😊

List all the keys and values


You can also clear and remove key\values in hashtable

Bunch of different objects in hashtable as also nested hashtable

Access the objects like .notation

Use .notation to access the nested hashtable

Note!
Hashtables are not ordered tables. If you want to show the table in order you created it you will need to
create ordered hashtable which is technicaly another object (Ordered Dictionary).
Splatting @
Splatting is a method of passing a collection of parameter values to a command as a unit. PowerShell
associates each value in the collection with a command parameter. Splatted parameter values are stored
in named splatting variables, which look like standard variables, but begin with an At symbol (@) instead
of a dollar sign ($). The At symbol tells PowerShell that you are passing a collection of values, instead of a
single value.

Splatting makes your commands shorter and easier to read. You can reuse the splatting values in
different command calls and use splatting to pass parameter values from the $PSBoundParameters
automatic variable to other scripts and functions.

Beginning in Windows PowerShell 3.0, you can also use splatting to represent all parameters of a
command.
You can also combine the parameters in splatting

Examples:
Add the key\pair value to the hastable and check if the key\value already exists using .Contain method.
Hashtable enumerator

In case that for example sorting is not working on hashtable you can use .GetEnumerator() method

PSDefaultParameterValues

Use this variable to set default paremeters globaly in your PS Profile


Using PowerShell ScriptBlocks
When using Invoke-Command parameters will be separeted by commas
PS is using often ScriptBlock in Jobs.
Scriptblocks are step ahead to Functions
Working with Objects in PowerShell

Object Fundamentals

Object members
Working with objects

Note!
All object have a .GetType method.
To get the members use Get-Member and to use get their names and values use Select-Object *

Powershell is mostly good with the type of the objects you are working in the pipeline. Sometimes you
need to give it a little help.

In this case we will take a look at the following example

PS can’t get a date from the variable as the variable contains data type string.

If you cast a data type (or strong declare?) you can get the right result

If you want to check data type you can use -is operator

Tell PS to treat this object as int32 and than perform the operation
Cast data type with -as operator or declare it before the variable (strongly type)

Another way to cast a data type in expression

Using .GetType object notation (method) to get the data type of the object

Using methods

Invoke the method using .notation

Use .notatation on all objects in the variable without foreach


In this example foreach will take substring at position (0) in length of (0,1) character and ivoke method
ToUpper. Afterthat it will take all from the position 1 (1)) and bcs there is not specified length he gets the
rest of the string.

Note!
Don’t look only for the method on what you can do with the object, search first for the Cmdlt that can do
that for you.

Note!
Discovering the members of the object. We can reference these properties trough .notation as .NET
objects

On the fly created properties using .NET code


To see the properties and methods of the object use Get-Member

Note!
To see the all properties and their values use Select-Object -Property *
Select the desired properties and group them on property

Custom Properties and Objects


Creating object on the fly with hash table Get-time

Creating the object with hash tables on the fly


Define property on the fly and use it in the line of code to sort the objects ad-hoc
(this property doesn’t exist but we created it on the fly).

Create “Tree size” function based on filtering of the custom properties on file system

Another example of creating the object property on the fly and grouping on it.

Custom Objects

First create a hash table which you will later turn to object
Now let’s create a custom object from the hash table and pipe it to tee and create and new variable

Another way to do this especially in scripting

Note!
When using pscustomobject will order the appearance of the object in the order you created them. In
addition to this example, you will not need to create additional hash table but create all in one step. This
is an example VS select object method.
Strings, Dates and Numbers

Common Object Transformations


Common Number Techniques

Note!
Casting data type [int32] has an effect of rounding the number.

Call the Math Class .NET and it’s use methods. Group them on the property Name to
get the clean view.

Call the Round Method


Manipulate variable and peform operation to change the data view ([math]::round
method

Advanced example of splating the first hash table $get and then transforming again
to hash table and at the end enumerating it.

Using .GetEnumerator() to manipulate and present the data


Example of number transformation and [math]::Round Method

Common String techniques

You might also like