0% found this document useful (0 votes)
6 views18 pages

PowerShell If-Else Logic Explained

Uploaded by

dev.stbei
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views18 pages

PowerShell If-Else Logic Explained

Uploaded by

dev.stbei
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PowerShell

Logic Control
Structures
INFO33192
Week 11
Types of Control Structures:

• Purpose of Control Flow Structures


• Testing a Condition (comparison /
logical operators)
• Logic (conditional) Statements (if,
Agenda if/else, if/elseif/else, switch)
Control Flow
Statements
A static script (one that does not change) has
limited usability.
Variables allow scripts to adapt to different
situations
There are also control flow statements (control
structures) that can be used to make a program
behave in different ways:
• Follow step-by-step from top to bottom
(sequential)
• Follows different paths based on logic
(conditional)
• Loop-around based on a condition (iterative)
Logic Statements –
Testing a Condition
For your PowerShell script to behave in different ways using a control flow statement, a
Conditional Test is performed which renders a Boolean Value of True or False.

Logic and looping statements work with conditional tests in order to take action (change
direction in sequence, or repeat sequence) based on the result of the test condition.

Examples of Conditional Tests:

• A variable equal to a specific value

• A variable not equal to a specific value

• A variable equal to another variable

• A variable less than a value

• A variable greater than or equal to a specific value

In PowerShell, test conditions are usually contained in round brackets: ( )


One exception is the switch statement where the test condition is contained in braces: {
}
Logic Statements – Comparison / Logical Operators
Examples:

The table displays common $CustomerAge = 34; $UserName = “Weaver”


$count = -23; $answer = “yes”

comparison and logical operators ($CustomerAge –gt 65)


False

used in conditional testing. ($UserName –eq “Weaver”)


True

($count –lt 0)
True

Comparison operators are used to ($answer –ne “yes”)

compare values (either stated or False

contained in a variable) to render a


result of true or false.

WARNING:
do not use symbols
=><
Comparison / Logical Operators
- Case-Sensitivity
Examples:
The –eq comparison operator
is case-INsensitive by default (‘abc' -eq ‘ABC‘)
True
To make it Case Sensitive, add
a "c" before the operator: (‘abc' -ceq ‘ABC‘)
False
-eq >>>> -ceq
Logic Statements – Logical Operators

Logical operators (on right-side of table) are used to test


multiple conditions.

–and both conditions must be true for True result:


e.g. ($ShoeSize –eq 12 –and $UserAge –ge 18)

–or only ONE condition has to be true, for True result


e.g. ($Guess –lt 1 –or $guess –ge 10)

Examples: The “!” symbol represents


(! $UserName –eq “Weaver”) negation or “opposite”.
False The –not logical operator
( $Username –not “Weaver”) produces the same outcome as
True
using the “!” operator.
Logic Statements – using un-typed variables
WARNING: Be careful when numerically testing un-typed variables.
The WRONG coding statement uses an un-typed variable.
If the script runs using that code and the user enters a string (e.g. “5”) instead of a number, the outcome could be
misleading.
To correct this potential problem, you can add [int] in front of the variable declaration to indicate the correct data-type of
the variable.

Wrong: Correct:

$x = Read-host "Enter a number over 10" [int] $x = Read-host "Enter a number over 10"
if ($x -gt 10){ if ($x -gt 10){
Write-host "The condition is true” Write-host "The condition is true”
exit exit
} }
else { else {
Write-host "The condition is false” Write-host "The condition is false”
} {
Testing a Condition:
“Reality Check”
Perform the following in the PS console pane on your VM:
1. Issue the following test condition: (3 == 3)
2. What is the result? Why? What is the correction?
3. Issue the following:
$number1 = 3
$number2 = read-host “enter a number”
4. Enter the string: “5” (when prompted) and issue the following:
($number1 –gt $number2)
5. What is the result? Why? What is the correction?
6. Write a condition (using logical operators) to test if the variable
called $number contains a value between 1 – 10.
7. Write a condition (using logical operators) to test the opposite of the
condition you performed in the previous step.
Control Flow Statements
– Logic (condition) statements
The logic statement determines the path for the
script to follow, based on the result of a
conditional test.
The logic statement is like a “fork in the road”:
the path (direction) that the script follows is
based on the result of the conditional test being
either true or false.
Types of Logic Statements:

If
if/else
If/elseif/else
Switch
Control Flow Statements: If True
?
False

The If Statement Syntax condition

Condition in
parentheses (…)

Cmd 1 Cmd 3

Cmd 2 Cmd 4

Notice: the commands are indented


Commands in within the if statement code block –
scriptblock {…} this makes the code more readable.
Control Flow
Statements: if/else
• The if/else Statement
• The instructions in the code block
(inside the braces) is run if the test
condition is True.
• If the condition is False, then the
code block (inside the braces) under the
else statement is run.
• This control structure is ideal if
only two alternative paths are possible.
Control Flow Statements:
if/elseif/else
• The if/elseif/else Statement
• Used for multiple paths.
• Where when the initial test is false, a new test
condition is tested and when that test condition is false,
testing continues.
• The elseif statement must NOT contain spaces
(i.e. “else if” is NOT permitted)
• At the end of an if/elseif statement, you include the
else statement as a “safety net”.
• These statements are useful for taking different
actions based on a range of values. An example is
creating a script to determine a letter grade from a
percentage mark, as you will see in the lab.
if-elseif-else statements:
“Reality Check”
Plan, Create, Run and Test the following PS Scripts on your VM:
1. Prompt the user for their age. Only display in your
console:
“Congratulations, you can retire” if they are 65 or over;
otherwise, do nothing.
2. Revise your script in the question #1 to display in your
console:
“You are too young, back to work!” if they are less than
65.
3. Revise your script from question #2 to display:
“You are too young, back to work!” if they are less than
65, but greater or equal to 16, and display “Aren’t you to
young to be working?” if you are less then 16 (Hint: use
logical operators).
Control Flow Statements: Switch

Switch Expression

Case
EQ
Switch is a compact form of IF Elseif Else Case 1 Code Block
1

Use if you have 4 or more Elseif statements. Switch makes the


code more readable EQ
Case
2 Case 2 Code Block
Switch evaluates each condition and can find multiple True
statements

Use the break command to exit the switch statement when a


condition is met. Use continue to go on to the next condition.
Case
EQ
Case n Code Block
Each switch statement can have one default statement which n
acts like the Else clause

Default Statement End


Control Flow Statements: Switch
PowerShell Monitoring Examples
• Performance Counters:
• Get-Counter '\Processor(_Total)\% Processor Time'

• Event Logs:
• Get-WinEvent -LogName Security -MaxEvents 10

• Export Results:
• Get-Process | Export-Csv C:\Logs\[Link]
1. There are 3 control structures:
sequential (step-by-step),
conditional (logic), and

What
iterative (loops).
Learning how to use these control structures to
solve tasks is the essence of
programming/scripting.
2. Conditional (logic) statements require a

have we condition to be tested which would render a true


or false outcome. There are various comparisons
and logical operators that can be used when
testing conditions.

learned? 3. Conditional (logic) Statements are:


• If
• If/Else
• If/Elseif/Else
• Switch

You might also like