Powershell – Conditional Statements across multiple lines

Background

Will like to provide working examples of how Powershell supports conditional statements; especially the ones that span multiple lines.

 

Outline

  1. Use back tick ( ` ) to indicate their is more
  2. Suffix the preceding line with the expression
    • Condition expression
      • -or
      • -and

 

Code


Set-StrictMode -Version Latest

$script:ErrorActionPreference = "Stop"

<#
  Declare constants
#>
Set-Variable stateCalifornia -option Constant -value "California";

Set-Variable cityCaliforniaLosAngeles -option Constant -value "Los Angeles";
Set-Variable cityCaliforniaSanDiego -option Constant -value "San Diego";
Set-Variable cityCaliforniaSantaBarbara -option Constant -value "Santa Barbara";
Set-Variable cityCaliforniaSantaClarita -option Constant -value "Santa Clarita";


Set-Variable stateNewYork -option Constant -value "New York";

Set-Variable cityNewYorkAlbany -option Constant -value "Albany";
Set-Variable cityNewYorkBuffalo -option Constant -value "Buffalo";
Set-Variable cityNewYorkNewYork -option Constant -value "New York";
Set-Variable cityNewYorkRochester -option Constant -value "Rochester";

<#
  Declare variables	
#>
[string] $state = $null;
[string] $city = $null;

[string] $log = "";

<#
  Set variables	
#>
$city = "Santa Clarita";
$city = "Albany";


<#
   Conditional Statements single line
#>
if ($city -eq $cityCaliforniaSantaClarita )
{
    $state = $stateCalifornia
}


<#
   Conditional Statements across lines using `
#>
if (
         ($city -eq $cityCaliforniaSantaBarbara ) `
     -or ($city -eq $cityCaliforniaSantaClarita )

   )
{
    $state = $stateCalifornia
}

<#
    Conditional Statements across lines using 'expectant'
	
	In this case we begin the secondary condition ( -or ) on the initial line
#>
if (
       ($city -eq $cityNewYorkAlbany ) -or

       ($city -eq $cityNewYorkBuffalo )
   )
{
    $state = $stateNewYork
}

$log = "The City of {0} is in {1}" -f $city, $state

Write-Output $log;


Source Code Control

GitLab

Powershell – Conditional Statements

powershell.conditional.multiLine.city.and.state.ps1

Link

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s