Learning and Sharing
  • Home
  • Blog
  • Linux
  • macOS
  • Virtualization
    • VMware
    • VirtualBox
  • Windows
    • Windows 11
    • Windows 10
    • Windows Server
  • Series
    • Symantec
    • Intune
    • Microsoft Azure
    • Powershell
    • VirtualBox
    • VMware
    • PowerShell Learning
    • Microsoft Graph
  • More
    • Auto Installation
    • AEC Installation
  • Contact
No Result
View All Result
  • Home
  • Blog
  • Linux
  • macOS
  • Virtualization
    • VMware
    • VirtualBox
  • Windows
    • Windows 11
    • Windows 10
    • Windows Server
  • Series
    • Symantec
    • Intune
    • Microsoft Azure
    • Powershell
    • VirtualBox
    • VMware
    • PowerShell Learning
    • Microsoft Graph
  • More
    • Auto Installation
    • AEC Installation
  • Contact
No Result
View All Result
No Result
View All Result

#14 PowerShell Learning: Conditional Logic in PowerShell

August 14, 2023
in Blog, PowerShell Learning
0
ADVERTISEMENT

Table of Contents

Like other programming languages, Windows PowerShell is a dynamic scripting language. Script code can be executed based on conditions that exist or occur. 

For example, a script might prompt for user input and run a block of code based on the data supplied by the user. A process or application may stop running, triggering an action within a script. Conditional Logic allows us to write scripts in a complex environment, it adds the intelligence required to create decision-making scripts.

Comparison Operators

Comparison operators let you specify conditions for comparing values and finding values that match specified patterns. To use a comparison operator, specify the values that you want to compare together with an operator that separates these values.

Windows PowerShell includes the following Comparison Operators:

  • –eq: Equal to
  • –lt: Less than
  • –gt: Greater than
  • –ge: Greater than or Eqaul to
  • –le: Less than or equal to
  • –ne: Not equal to
  • –like: Match using the wildcard character (*)
  • –NotLike: Does not match using wildcard character (*)
  • –Match: Matches a string using regular expressions
  • –NotMatch: Does not match a string. Uses regular expressions
  • –Contains: Tells whether a collection of reference values includes a single test value.
  • –NotContains: Tells whether a collection of reference values not includes a single test value.

When comparing text strings, by default PowerShell is not case-sensitive. This means JOHN and john would compare equal to -eq.

However, you can force PowerShell to compare values based on case-sensitivity. By appending an i to the operator, you can tell Windows PowerShell to be case-insensitive and by appending c forces Windows PowerShell to be case-sensitive.

For example:

John -eq JOHN   #The result is “True”
John -ieq JOHN  #The result is “True”
John -ceq JOHN  #The result is “False“

Windows PowerShell also supports the use of following logical operators:

83Y6HhvAZQKVA87mU75M2t6FFVJzuPiUIC4MInTqKCAxypKb22AsqT0XDzcJ

The result of each operator is either True or False. The results can be used in the PowerShell scripts for decision-making process.

Conditional Logic

When writing PowerShell scripts, we need a way to apply comparison results with conditional logic (the decision-making process). PowerShell supports two logic statements:

  • if : You can use the if statement to run code blocks if a specified conditional test evaluates to true.
  • switch : The switch statement is equivalent to a series of If statements, but it is simpler. The Switch statement lists each condition and an optional action. If a condition obtains, the action is performed.

If Statement

  • You can use the If statement to run code blocks if a specified conditional test evaluates to true.
  • You can also specify one or more additional conditional tests to run if all the prior tests evaluate to false.
  • Finally, you can specify an additional code block that is run if no other prior conditional test evaluates to true.

The following example shows the syntax of If statement:

if (<condition1>) {<statement list 1>}
elseif (<condition2>) {<statement list 2>}
else {<statement list 3>}
  1. When you run an If statement, Windows PowerShell evaluates the <condition1> conditional expression as true or false. If <condition1> is true, <statement list 1> runs, and Windows PowerShell exits the If statement.
  2. If <condition1> is false, Windows PowerShell evaluates the condition specified by the <condition2> conditional statement.  If <condition2> is true, <statement list 2> runs, and Windows PowerShell exits the If statement.
  3. If both <condition1> and <condition2> evaluate to false, the <statement list 3>code block runs, and Windows PowerShell exits the If statement.

You can use multiple Elseif statements to chain a series of conditional tests so that each test is run only if all the previous tests are false. If you need to create an If statement that contains many Elseif statements, consider using a Switch statement instead.

Example:

The following script asks the user to enter the name of windows process and then compares the user input to the list of running processes on computer. If user input matches to any of running process, the process is displayed. If there is no matching process found, a message will be displayed that the process is not running on system.

$name = Read-Host "Please enter the name of Windows Process"
$ps = Get-Process -ErrorAction SilentlyContinue | Where-Object {$_.Name -match "$name"}
If (-Not $ps) {
    Write-Host "The process $name is not running on this computer"
}
Else {$ps}

You can copy and paste the above code into notepad, vs code or PowerShell ISE and save the file with .ps1 extension.

#Output

PS D:\> .\myscript.ps1
Please enter the name of Windows Process: firefox
The process firefox is not running on this computer
PS D:\> 
PS D:\> .\myscript.ps1
Please enter the name of Windows Process: notepad

Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
-------  ------    -----      -----     ------     --  -- -----------
    761      35    83956      82880       7.13  11576   1 Notepad

Switch Statement

To check multiple conditions, you can use a switch statement. The Switch statement is equivalent to a series of If statements, but it is simpler. The Switch statement lists each condition and an optional action. If a condition obtains, the action is performed.

A basic switch statement has the following format:

Switch (<test-value>) {
    <condition> {<action>}
    <condition> {<action>}
}

For example, the following script takes the Computer Name as user input and then queries the WMI store on computer and reports the role of computer by using DomainRole property of object.

$cn = Read-Host "Please enter the Computer Name"
$obj = Get-WmiObject -Class win32_ComputerSystem -ComputerName $cn
Write-Host "Computer: $cn is a"
Switch ($obj.domainRole) {
    0 {"Standalone Workstation"}
    1 {"Member Workstation"}
    2 {"Standalone Server"}
    3 {"Member Server"}
    4 {"Backup Domain Controller"}
    5 {"Primary Domain Controller"}
    default {Write-Host "The role can not be determined"}
}
#Output

PS E:\> .\myscript.ps1
Please enter the Computer Name: dc01
Computer: dc01 is a
Primary Domain Controller
PS E:\>
PS E:\> .\myscript.ps1
Please enter the Computer Name: hr-pc001
Computer: hr-pc001 is a
Member Workstation

Conditional logic is the foundation for dynamic PowerShell scripting. I have briefly introduced you that how you can control the flow of a script based on conditional responses.

5/5 - (1 vote)
Previous Post

#13 PowerShell Learning: PowerShell Loops

Next Post

#15 PowerShell Learning: PowerShell Functions

Related Posts

Running Hyper-V and VMware Workstation on The Same Machine

August 15, 2024

How to Uninstall All Autodesk Products At Once Silently

July 29, 2024
Ftr5

How to Uninstall the Autodesk Genuine Service on Windows

July 29, 2024
Ftr19

How to Fix Windows Cannot Read the ProductKey From the Unattend Answer File in VirtualBox

July 26, 2024
Ftr25

How to Update Windows Terminal in Windows 10/11

July 26, 2024

How to Disable The Beep Sound in WSL Terminal on Windows

July 26, 2024

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • How To Turn On uBlock Origin Extension in Chrome (2025)
  • Images Hidden Due To Mature Content Settings In CivitAI
  • Azure OpenAI vs Azure AI Hub, How to Choose the Right One for Your Needs

Categories

Stay in Touch

Discord Server

Join the Discord server with the site members for all questions and discussions.

Telegram Community

Jump in Telegram server. Ask questions and discuss everything with the site members.

Youtube Channel

Watch more videos, learning and sharing with Leo ❤❤❤. Sharing to be better.

Newsletter

Join the movement and receive our weekly Tech related newsletter. It’s Free.

General

Microsoft Windows

Microsoft Office

VMware

VirtualBox

Technology

PowerShell

Microsoft 365

Microsoft Teams

Email Servers

Copyright 2025 © All rights Reserved. Design by Leo with ❤

No Result
View All Result
  • Home
  • Linux
  • Intune
  • macOS
  • VMware
  • VirtualBox
  • Powershell
  • Windows 10
  • Windows 11
  • Microsoft 365
  • Microsoft Azure
  • Microsoft Office
  • Active Directory

No Result
View All Result
  • Home
  • Linux
  • Intune
  • macOS
  • VMware
  • VirtualBox
  • Powershell
  • Windows 10
  • Windows 11
  • Microsoft 365
  • Microsoft Azure
  • Microsoft Office
  • Active Directory