Search notes:

PowerShell: if, if else, if elseif else

The if statement conditionally does or does not execute a set of other statements.
Unlike C, the curly braces are always required (even if only one statement is controlled by the if statement).

Simple if statement

A simple if statement only executes a set of statements if the condition cond is true.
if (cond) {
  statement
 [statement]
}

If else statement

An if … else statement executes a series of statement if the condition is true and another set of statement is not true.
if (cond) {
  statement
 [statement]
}
else {
  statement
 [statement]
}
Simple if ($cond) { $expr_true } else { $expr_false} statements can be abbreviated with the ternary operator ($cond ? $expr_t : $expr_f). The ternary operator was introduces with PowerShell 7.

if elseif else

An if, elseif, …, else statement allows to check a series of conditions (cond_1, …, cond_n) and executes the body of the first condition that is true.
If no condition is true, the else body is executed. The else body is optional.
if (cond_1) {
  statement
 [statement]
}
elseif(cond_2) {
  statement
 [statement]
else {
  statement
 [statement]
}

Negations

A condition is negated with the -not operator:
if (-not cond) {
  statement
 [statement]
}
-not can be abbreviated with the exclamation mark (!), thus the following code fragment is equivalent to the previous one:
if (! cond) {
  statement
 [statement]
}
If the return value of a cmdLet needs to be negated, the cmdLet must be in parentheses:
if (-not (test-path $txtFile)) {
   write-output "$txtFile does not exist"
}

An if statement may evaluate to a value

An if statement may evaluate to a value which can be, for example, assigned to a variable.
$val = if (2 -gt 1) { 'yes' } else { 'no ' }   

See also

Comparison and logical operators.
Other statements such as the switch statement.

Index

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/Windows/...', 1740453729, '18.225.57.152', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/Windows/PowerShell/language/statement/if/index(122): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78