PowerShell 7 Fundamentals by Jeff Hicks
PowerShell 7 Fundamentals by Jeff Hicks
Jeff Hicks
Notes by Zlatan Petrovic
2023-2024, Zürich
~ Table of contents ~
Requirements
Release Channels and Updates
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
Hosting options are between classic CMD console and newer Windows terminal
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.
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
Version Check
The PowerShell way
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
Understanding Help
Discovering PS Commands
Command Types
Command Naming Conventions
Command Aliases
Note!
Get and invoke history
Note!
Get+Psreadlineoption
If this is not working for you (for whatever reason) you can switch it off using this command:
I for one welcome our intelligent command line suggestions and would advise switching it on!
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
What is an Object?
Working with Objects in the Pipeline
Note!
Everytinng is an Object! One command to measure all the objects!
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
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 “%”
Let’s first create two files and then invoke .encrypt method on both of them trough ForEach-Object
Filtering with PowerShell
Note!
Simplyfied syntax for Where-Object calling the object Name
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
Module introduction
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
Module Summary
Working with Registry and Certificates with PSDrive
Module Introduction
To delete the reg key, you need first to clear the data from the key
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
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
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 > $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>.
Unary Operators
Unary operators increase or decrease the value of a variable by 1.
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 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
Comparison Operators
Match and Notmatch Operator
Math and Range Operators
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)
Null Operators
Type operators
Special operators
Using Arrays and Hashtables
!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
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
If you try to play stupid, you can test the ++ operator on string 😊
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
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.
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)
Using .GetType object notation (method) to get the data type of the object
Using methods
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
Note!
To see the all properties and their values use Select-Object -Property *
Select the desired properties and group them on property
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
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
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.
Advanced example of splating the first hash table $get and then transforming again
to hash table and at the end enumerating it.