Background
Will like to provide working examples of how Powershell supports conditional statements; especially the ones that span multiple lines.
Outline
- Use back tick ( ` ) to indicate their is more
- Suffix the preceding line with the expression
- Condition expression
- -or
- -and
- Condition expression
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;