Conditional Statements

The if statement

In this lession we will learn about conditional flow of the code. PowerShell supports various conditional statements like if, if-else, if-elseif and switch conditional statements.

The if statement will evaluate the given condition and based on the result of the condition it will decide which code block to execute.

For example if we want to check users age and based on the age we want to display the result then we use if condition as below

Example
$age = 3;
if ($age -gt 2)
{
	return "You need to purchase a ticket";
}

If-Else statement

We can use if else condition if we want to execute either of the code blocks. For example if we want to tell user that if you want to subscribe for the services then you need to do payment else payment is not required. We can write code as below

Example
$subscribeForService = $True;
if ($subscribeForService)
{
	return "You need to make a payment for subscription";
}
else
{
	return "You can skip this step";
}

In if and if-else condition we can use any operators which returns boolean

We can also evaluate more than 1 condition in single if statement with the help of logical operator. If we want to check wether user has 18 year old and has voter id card then user can vote else user can't vote then we can check like this.

Example
$age = 18;
$hasVoterId = $True;
if($age -ge 18 -and $hasVoterId -eq $True)
{
	return "you can vote";
}
else
{
	return "you can't vote";
}

If and Else-if statement

We can use if and else-if statement if we have multiple conditions to evaluate as below.

Example
$age = 18;
$hasVoterId = $False;
if($age -ge 18 -and $hasVoterId -eq $True)
{
	return "You can vote";
}
elseif($age -ge 18 -and $hasVoterId -eq $False)
{
    return "Please apply for voter id.";
}
else
{
	return "You can't vote";
}

The switch statement

If we have more than 2-3 conditions then it's better to use switch statement. It is similar to the other languages like C or C++. In switch statement we need to define 1 case for each condition. Please note that in PowerShell we dont require to put break statement.

Example
function Greet-Person
{  
    [CmdletBinding()]  
    Param (  
        [ Parameter (Mandatory = $true)]  
        [string] $Name  
    )  
 
    Process
    {
        $currentHours = Get-Date -Format "HH";
        $greet = "Good Evening";

        if ($currentHours -ge 0 -and $currentHours -lt 12) {
            $greet = "Good Morning";
        }
        elseif ($currentHours -ge 12 -and $currentHours -lt 16){
            $greet = "Good Afternoon";
        }


        Write-Host ($greet + " " + $Name + "!")
    }
}

Greet-Person "Jack";

CmdletBinding() attribute has been used above to make function act like Cmdlet commands.

 

← Previous

Next →