If...ElseIf, and Else

First, we will take a look at the conditional operators. You will need conditions in most of your scripts, when you validate different possibilities or want to make sure that all of the conditions for starting the next operations are met. For simple conditions, you will use the if statement. Let's take a look:

# starting with the if keyword and followed by the condition in parentheses
if (conditional statement)
{
#if conditional statement was
}
#the else area is optional
else
{
#if conditional statement was not met
}

The construct always starts with the if keyword, followed by the conditional statement in parentheses, and then the first statement, which will run if the statement was met. The else area is optional, and will be run through if the condition was not met. The conditional statement can be created with any logical operators, as previously described. 

In the next, more practical examples, we will initialize two variables, $emptyVariable and $variableForConditionsand test some conditions on them:

# creating variable for common test
$emptyVariable = ""
$variableForConditions = "Test123"

# To validate, if a string has been correctly filled, you can use this method.
# You can try to replace the $emptyVariable with $variableForConditions and testing it again.
if ($emptyVariable -eq "")
{
#empty
Write-Output 'empty' # <---
}
else
{
#not empty
Write-Output 'not empty'
}

A short-written way to validate whether objects are empty is as follows:

# short-written
if ($emptyVariable)
{
#not empty
Write-Output 'not empty'
}
else
{
#empty
Write-Output 'empty' # <---
}

You can also negate it, as follows: 

# short-written negated
if (-not $emptyVariable)
{
#empty
Write-Output 'empty' # <---
}
else
{
#not empty
Write-Output 'not empty'
}

Another keyword is elseif, which just adds another condition to the condition chain. You can easily add more than one condition to another with the elseif keyword, which is followed by the conditional statement.

It can be realized as follows:

# like statement and condition chain
# validate if $variableForConditions is like 'test0*'

if ($variableForConditions -like 'test0*')
{
#not like "Test*'"
Write-Output 'like "Test*"'
}
# validate if $variableForConditions is like 'Test*'
elseif ($variableForConditions -like 'Test*')
{
#-like 'Test*'
Write-Output '-like Test*' # <---
}
else
{
#something else
Write-Output 'something else'
}

For more complex condition chains, or for using more filters, you should use the switch statement instead.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.81.94