PowerShell : Conditional Statements

Like most programming languages, PowerShell uses the keywords if/else and switch to execute statements (cmdlets/functions) that are dependent on certain conditions.

if statement

An if statement consists of a Boolean expression followed by one or more statements.

If statement executes the code only when a specified conditional test evaluates to true.

$a = 100
if ($a -gt 50)
{
Write-Host "The value of $a is greater than 50"
}
cd $HOME\Desktop
if (Test-Path test.txt)
{
Get-Content test.txt
}

if-else statement

An if statement can be followed by an else statement, which executes when the Boolean expression is false.

if-else

cd $HOME\Desktop
if (Test-Path hello.txt)
{
Get-Content hello.txt
}
else{
Write-Host "File Not found"
}

if-elseif-else

cd $HOME\Desktop
if (Test-Path hello.txt)
{
Get-Content hello.txt
}
elseif(Test-Path test.txt)
{
Get-Content test.txt
}
else{
Write-Host "Both files not found"
}

nested if statement

You can use if or else-if statement inside another if or else-if statement(s).

$code = 200
$status ="Completed"

if ($status -eq "Completed")
{
   if ($code -eq 100)
   {
      Write-Host "Job completed Successfully"
   }
   else
   {
      Write-Host "Job completed with errors"
   }
}
else 
{
   Write-Host "Job not completed"
}

Output: Job completed with errors

switch statement

A switch statement allows a variable to be tested for equality against a list of values.

$status_code = 200
switch ($status_code)
{
100 { Write-Hots "Success"}
200 { Write-Host "Warning" }
300 { Write-Host "Error" }
}

Output: Warning

Advertisements

Learn Technology

%d bloggers like this: