Programming Question

What is a PowerShell pipeline? Show an example.
NOTE -The source files for the programs shown in
this presentation are in contained in
PowerShell_Presentation_Files.zip available in
the PowerShell folder under Course Content.
CPT 180 – WEEK 7
Introduction to
PowerShell
What is PowerShell?




Microsoft’s task automation framework and primary management tool.
Consists of a command-line shell and a robust scripting language.
Enables administrators to perform tasks on local and remote machines.
Built on top of the Windows .Net framework.
PowerShell Environment

PowerShell can be used in several environments such as:
 PowerShell CLI (Command Line Interface) – used for one-off scripting
 PowerShell ISE (Integrated Scripting Environment) – used for one-off
scripting and the creation of reusable scripts.
 Visual Studio Code – full-featured .Net editor that can be used to create
PowerShell scripts.
PowerShell Basics

PowerShell is a Command Line interpreter and a scripting
environment.

PowerShell commands are called Cmdlets. Cmdlets are verb-noun
pairs separated by a hyphen.

PowerShell is object-based, not text-based.

Most PowerShell Cmdlets return an object that can be piped
(passed) to another Cmdlet.
PowerShell Versions

PowerShell 1.0 – Support for Windows XP and Server 2003.

PowerShell 2.0 – Support for Windows 7 and Server 2008.

PowerShell 3.0 – Support for Windows 8 and Server 2012.

PowerShell 4.0 – Support for Windows 8.1 and Server 2012 R2.

PowerShell 5.0 – Support for Windows 10.

PowerShell 5.1 – Support for Windows 10 Anniversary Update and
Server 2016.

PowerShell Core 6.0 – Open-Source, cross-platform provides support
for Windows, LINUX and Mac OS’s. Built on top of .Net core instead
of Windows .Net framework.
Using PowerShell in Windows 10

The Windows 10 Anniversary Update comes with PowerShell 5.1
installed and ready for use.

The PowerShell and PowerShell ISE Icons should appear on the Start
Menu. If not, type in PowerShell and ISE, respectively.
Using PowerShell in Windows 8

On Windows 8.1 and Windows 8, the Windows PowerShell 2.0 Engine feature is
turned on by default. However, to use it, you need to turn on the option for
Microsoft .NET Framework 3.5, which it requires.

To turn on .NET Framework 3.5

On the Start screen, type Windows Features.

On the Apps bar, click Settings, and then click Turn Windows features on or off.

In the Windows Features box, click .NET Framework 3.5 .

To turn the Windows PowerShell 2.0 Engine on and off

On the Start screen, type Windows Features.

On the Apps bar, click Settings, and then click Turn Windows features on or off.

In the Windows Features box, expand the Windows PowerShell 2.0 node, and
click the Windows PowerShell 2.0 Engine box to select or clear it.

The PowerShell and PowerShell ISE Icons should appear on the Start Menu. If
not, type in PowerShell and ISE, respectively.
Downloading PowerShell on mac OS
1.
Using your browser, navigate to the Microsoft PowerShell site.
https://docs.microsoft.com/en-us/powershell/
2.
3.
4.
5.
6.
7.
Click on Setup and Installation.
Click on Installing PowerShell Core on macOS.
Scroll down to the section named “Installation via Direct Download”.
Click on releases in the first sentence of the section.
Scroll down to the section named “Assets”.
Click on the file named:
powershell-6.2.1-osx-x64.pkg
8.
9.
The file should download to your computer.
After it downloads, click the arrow next to the file name and click
Open.
Installing PowerShell on mac OS
1.
After the installation package downloads, click the arrow next to the
file name and click Open.
2.
This should open the “Welcome to the PowerShell – 6.2.1 Installer”
window.
3.
Click Continue.
4.
This will open the “Select a Destination” Window.
5.
Click Continue.
6.
This will open the “Installation Type” window.
7.
Click Continue for standard installation.
8.
If prompted for your password, enter and Click Install Software.
9.
When the installation is complete, Click Close.
Starting PowerShell

Always start PowerShell as an Administrator on Windows.

Right Click on the PowerShell Icon and select “Run as Administrator”. On mac OS, just
double click the PowerShell icon.

In order to allow PowerShell to load and run scripts, you must set the PowerShell
execution policy. In order to do this, you should run the following command:
Set-ExecutionPolicy –ExecutionPolicy RemoteSigned
Cmdlets
Cmdlets – the basic unit of PowerShell functionality
 Verb-Noun pairs separated by a hyphen.
 Case insensitive
 Nouns are always singular
 Many of the Cmdlets can be accessed using an alias (frequently from DOS or BASH)
 Examples:

Get-Command
(lists all PowerShell commands), alias – gcm

Get-ChildItem
(list the current directory), aliases – gci, dir, ls
Cmdlet Parameters

Cmdlets can accept zero or more parameters.

Some cmdlets have one or more required parameters.

Parameters are normally given as a name-value pair.

The parameter name is proceeded by a dash (-).

Parameters can be passed positionally but should only be used for simple commands
typically with only one or two parameters.

Examples:
 Gets help on the Get-ChildItem command using the –Name parameter
Get-Help –Name Get-ChildItem
 Gets the last 10 entries in the System log using the –Logname and –Newest parameters
Get-EventLog –Logname System –Newest 10
Cmdlet Examples
Get-Help –Name Get-Command
Gets help on Get-Command
Cmdlet Examples
Get-Command –Name Write*
Gets all of the Write commands
Cmdlet Examples
Get-ChildItem –Path G:\eclipse
Gets all of the items located in the G:\eclipse directory
Get-ChildItem Cmdlet
 Get-ChildItem – Used to get items from a specified
location.
 Common Parameters
 -Path – specifies the path to a location (The default is
the current directory.)
 -file
– will only return file names (no directory names)
Get-ChildItem Example
Read-Host Cmdlet
 Read-Host – Used to read text from the console and
assign it to a variable. It always returns a string.
 Common Parameters
 -Prompt
– specifies the text of the prompt
 -AsSecureString
– will cause asterisks to appear on
the console in place of the characters that the user
types as input.
Read-Host Example
Write-Output Cmdlet
 Write-Output – Used to write output to the output stream.
 Common Parameters
 -InputObject
– specifies the object
Write-Output Example
PowerShell Pipelines
 Pipelines act like a series of connected segments of
pipe.

Items moving along the pipeline pass through each
segment.
 To create a pipeline in PowerShell, you connect
commands together with the pipe operator “|”.
 The result (an object) from one Cmdlet is passed to
another Cmdlet.
 This process is known as piping.
Write-Host Cmdlet
 Write-Host – Used to write customized output to the console.
 Common Parameters
 -Object
– specifies the object to be sent to the console
 -ForegroundColor
– specifies the font color
 -BackgroundColor
– specifies the background color
Write-Host Example
This shows the piping of an object from one Cmdlet to another.
Get-Content Cmdlet
 Get-Content – Used to get content from a text file.
 Common Parameters
 -Path
– specifies the path to the file
 -TotalCount
retrieve
– specifies the number of lines to
Get-Content Example
This shows the piping of an object from one Cmdlet to another.
Add-Content Cmdlet
 Add-Content – Used to add content to a text file.
 Common Parameters
 -Path
 -Value
– specifies the path to the file
– specifies the content to be added
Add-Content Example
This code first displays the content of the cpt180.txt file, then
adds a line to it, and then displays it again.
Test-Path Cmdlet
 Test-Path – Used to check if a path exists. If the path
exists, it returns $True, if it does not exist, it returns $False.
 Common Parameters
 -Path
– specifies the path to be checked
Test-Path Example
This code stores the file path in a variable. It then checks if the
file path exists and stores the result in a second variable. It then
displays the result.
PowerShell Comments

Comments can be added to your PowerShell code by using
the appropriate symbol.

Comments are ignored by the Python interpreter.

You can create single-line comments by using a hash
character (#).

You can create multi-line comments by using
Examples:
#using the Write-Output
Cmdlet
Write-Output –InputObject “My name is Joe.” # writes my name to the screen
Variables

PowerShell lets you create named objects known as variables.

Variable names can include the underscore character and any alphanumeric
characters.

A variable is always declared using the $ character followed by variable name.

Variables are case-insensitive.

Examples of valid variable names are:
$FirstName
$loc
$last_name
$Month12
Data Types
 PowerShell is dynamically typed which means that the
variables’ data type is automatically assigned based on
the assigned value when the variable is initialized.
 PowerShell data types include string, integer, floating-
point, and Boolean.
 There are two built-in Boolean variables. They are $true
and $false.
Data Type Conversion

In PowerShell, variables can be changed from one data type to
another by using the cast operator. (square brackets)

Examples
 $x = “100.50”
$x is a string with a value of “100.50”
 $y = [int]$x
$y is an integer with a value of 100″
 $z = [decimal]$x
$z is a decimal (floating point) with a value of 100.50
Variables Example

String Variables

$length = 5.5
$pi = 3.141592
$capacity = 456.75
$firstName = “John”
$favCar = “Chevrolet Camaro”
$location = “G:\CPT189\Scripts\list.txt”

Integer Variables
$counter = 5
$temp = -15
$age = 45
Floating-Point Variables

Boolean Variables
$paid = $true
$condition = $false
PowerShell Operators

An operator is a symbol or keyword that performs some
type of calculation, comparison, or assignment of one or
more values.

There are four primary types of PowerShell operators:
 Arithmetic
 Assignment
 Comparison
 Logical
Arithmetic Operators
 Perform mathematical operations.
 There are five arithmetic operators:
 + (addition)
 – (subtraction)
 * (multiplication)
 / (division)
 % (modulus)
Assignment Operators
 Every assignment operation either initializes
(initially assigns) or changes the contents of
the variable listed on the left side of the
operator. Operator
Description
Example
=
Simple assignment
operator. Assigns values
from right side operands
to left side operand.
$c = $a + $b will
assign value of
$a + $b into $c
+=
Add AND assignment
operator. It adds right
operand to the left
operand and assign the
result to left operand.
$c += $a is
equivalent to
$c = $c + $a
-=
Subtract AND
assignment operator. It
subtracts right operand
from the left operand
and assign the result to
left operand.
$c -= $a is
equivalent to
$c = $c – $a
Comparison Operators
 Allow you to compare two values.
 Result of a comparison is always a
Boolean value ($true or $false).
Comparison Operators (Cont.)
Assume
$x = 5
Operator
Description
Comparing
-eq
equal to
-ne
-gt
-lt
-ge
-le
not equal
greater than
less than
greater than or equal to
less than or equal to
$x -eq 5
$x -eq 6
$x -ne 8
$x -gt 8
$x –lt 5
$x -ge 8
$x -le 5
Returns
$true
$false
$true
$false
$false
$false
$true
Logical Operators

Also known as Boolean operators.

Compares two or more Boolean values or
comparison statements.

Result is always a Boolean value ($true or $false).

There are three logical operators:
 -AND – Returns true if all conditions are true.
 -OR – Returns true if any condition is true.
 -NOT – Returns true if condition is false and
returns false if a condition is true.
Logical Operators (Cont.)
Assume
$x = 6
$y = 3
Operator
Examples
Returns
-AND
($x -lt 10 -AND $y -gt 1)
$true
-AND
($x -lt 10 -AND $y -eq 1)
$false
-OR
($x -eq 5 -OR $y -eq 5)
$false
-OR
($x -eq 5 -OR $y –eq 3)
$true
-NOT
-NOT($x -eq $y)
$true
Flow Control Statements
 A flow control statement is a statement that you can
use to execute code based a condition or group of
conditions.
 It allows a program to make decisions based on
these conditions.
 The only PowerShell flow control statement we
will look at is the if-else structure.
if / else statement
 The If/Else statement block consists of 4 parts:
1.
the if statement
2.
the comparison
3.
the code to execute if the comparison returns $true
4.
an optional else block containing code to be
executed if the comparison returns $false
if / else statement (Cont.)
comparison is contained within parenthesis
if statement
else statement
if (comparison){
Code
}
else{
Code
}
code to be
executed if
comparison is true is
contained within
curly braces
code to be
executed if
comparison is false is
contained within
curly braces
Writing the Code for an If statement
 Assume that you want to write a program that will respond
to a user after the user enters their name.
 If their name is “Sally”, the program will respond with “Hi
Sally. That is my name too!”.
 If their name is anything else, the program will respond with
a greeting using the name entered such as “Hi John.”
 The program must make a decision before it can display
the proper message.
 The decision is based on name entered by the user.
if Example 1-1
$name = Read-Host -Prompt “What is your name?”
$response = “”
if($name -eq “Sally”){
$response = “That is my name too!”
}
Write-Output -InputObject (“Hi ” + $name + “. ” + $response)
results in
If the user enters
“Sally”, the code
contained in the if
block is executed.
Hi Sally. That is my name too!
if Example 1-2
$name = Read-Host -Prompt “What is your name?”
$response = “”
if($name -eq “Sally”){
$response = “That is my name too!”
}
Write-Output -InputObject (“Hi ” + $name + “. ” + $response)
results in
Hi John.
If the user enters
“John”, the code
contained in the if
block is not
executed.
Writing the Code for an if/else Statement
 Assume that you want to write a program that
will calculate the final price of an item that is
being purchased by a customer.
 Because of a special sale that has just started, if
the price of the item is greater than 100 dollars,
the customer receives a 10% discount.
 The program will then print out the final price of
the item.
 The program must make a decision before it can
make the proper calculation.
 The decision is based on the price of the item.
if Example 2-1
$price = Read-Host -Prompt “What is the price?”
$price = [int]$price
$discount = 10
if($price -gt 100){
$final_price = $price – $discount
Write-Output -InputObject “You receive a discount today!”
}
else{
$final_price = $price
Write-Output -InputObject “Discounts are available on purchases
over 100 dollars.”
}
Write-Output -InputObject (“Your final price is ” + $final_price + “.”)
results in
Assume the user
enters 150. Because
the value of price is
greater than 100,
the code contained
in the if block is
executed
You receive a discount today!
Your final price is 140.
if Example 2-2
$price = Read-Host -Prompt “What is the price?”
$price = [int]$price
$discount = 10
if($price -gt 100){
$final_price = $price – $discount
Write-Output -InputObject “You receive a discount today!”
}
else{
$final_price = $price
Write-Output -InputObject “Discounts are available on purchases
over 100 dollars.”
}
Write-Output -InputObject (“Your final price is ” + $final_price + “.”)
Assume the user
enters 90. Because
the value of price is
not greater than
100, the code
contained in the
Else block is
executed
results in Discounts are available on purchases over 100 dollars.
Your final price is 90.
Example 3 – Writing the Code for an if/else Statement
 Assume that you want to write a program that will check if
two files exist and if the user has read permission for these
files.
 If this is true the program will display the contents of the
two files.
 If this is false, the program will display a message.
 The program must make a decision before it can
determine what to do.
 The decision is based on the existence of the files and
their set read permissions.
Contents of the text files
if Example 3-1
$file1 = “.\colors.txt”
$file2 = “.\shapes.txt”
$filesExist = (Test-Path -Path $file1) -AND (Test-Path -Path $file2)
if ($filesExist -eq $True)
{
Write-Output -InputObject “COLORS”
$file_content = Get-Content -Path $file1
Write-Output -InputObject $file_content
Write-Output -InputObject “SHAPES”
$file_content = Get-Content -Path $file2
Write-Output -InputObject $file_content
}
else
{
Write-Output -InputObject “One or more of the required files cannot be read!”
}
results in
COLORS
red
green
blue
SHAPES
circle
square
triangle
Because both files
exist, the code
contained in the if
block is executed
and the files’
contents are
displayed.
if Example 3-2
$file1 = “.\colors.txt”
$file2 = “.\shapes.txt”
$filesExist = (Test-Path -Path $file1) -AND (Test-Path -Path $file2)
if ($filesExist -eq $True)
{
Write-Output -InputObject “COLORS”
$file_content = Get-Content -Path $file1
Write-Output -InputObject $file_content
Write-Output -InputObject “SHAPES”
$file_content = Get-Content -Path $file2
Write-Output -InputObject $file_content
}
else
{
Write-Output -InputObject “One or more of the required files cannot be read!”
}
results in
Because one file
does not exist, the
code contained in
the else block is
executed and the
message is displayed.
One or more of the required files cannot be read!
Writing Scripts
 PowerShell scripts can be written using any text
editor.
 PowerShell ISE contains a text editor that can be
used for creating and running PowerShell scripts.
 PowerShell scripts have a file extension of ps1.
Running Scripts
 PowerShell scripts can be run from the PowerShell prompt by
typing in the script file name along with a path. If the file is in
the current directory, use ./ as the path.
 PowerShell scripts can be run from the Windows Command
Prompt by typing in PowerShell –File filename.ps1.
 Before running PowerShell scripts, you must give permission to
run the scripts by running the following PowerShell command:
Set-ExecutionPolicy –ExecutionPolicy Unresticted
Writing a Script Step by Step using Windows PowerShell ISE
 Step 1 – Understand the Problem
 The example script will do the following:
 Check to see if a file named users.txt exists.
 If it does exist, print out the contents to the console.
 If it does not exist, print a message stating that the
file cannot be found.
 Add appropriate comments
Writing a Script Step by Step using Windows PowerShell ISE
 Step 1 – Understand the Problem – Continued
 The users.txt file (located in the myuser folder) looks like:
If you wish to write and run this script example (highly recommended), copy
the myusers folder to the root directory of a local or USB drive such as:
G:\myusers
Writing a Script Step by Step using Windows PowerShell ISE
 Step 2 – Open Windows PowerShell ISE as
Administrator
Script Pane
PowerShell
Cmdlet List
PowerShell
Command
Prompt
Writing a Script Step by Step using Windows PowerShell ISE
 Step 3 – Write the code and save the file as
checkForUserFile.ps1
Writing a Script Step by Step using Windows PowerShell ISE
 Step 4 – Run the Script by hitting F5 (or entering the full
path of the script file).
Writing a Script Step by Step using an Editor in macOS
(Example shown using mac OS and TextEdit)
 Step 1 – Understand the Problem
 The example script will do the following:
 Check to see if a file named users.txt exists.
 If it does exist, print out the contents to the console.
 If it does not exist, print a message stating that the
file cannot be found.
 Add appropriate comments
Writing a Script Step by Step using an Editor in macOS
 Step 1 – Understand the Problem – Continued
 The users.txt file (located in the myusers folder) looks like:
If you wish to write and run this script example (highly recommended), copy the
myusers folder to your Documents directory such as:
/Users/your_user_name/Documents/myusers
Writing a Script Step by Step using an Editor in macOS
 Step 2 – Open TextEdit
Writing a Script Step by Step using an Editor in macOS
 Step 3 – Write the code and save the file to your Documents folder
such as: /Users/your_user_name/Documents/checkForUserFile.sh:
Writing a Script Step by Step using an Editor in macOS
 Step 4 – Open PowerShell and Run the script by entering
the full path of the script file.
The End

Save Time On Research and Writing
Hire a Pro to Write You a 100% Plagiarism-Free Paper.
Get My Paper
Still stressed from student homework?
Get quality assistance from academic writers!

Order your essay today and save 25% with the discount code LAVENDER