If

Conditionally perform a command.

Syntax
      if ( condition ) { commands_to_execute }
      [ elseif ( condition2 ) { commands_to_execute } ]
      [ else {commands_to_execute} ]

Key
   Condition  An expression that will evaluate to true or false,
              often utilising one or more comparison operators.

   commands_to_execute
              A PowerShell or external command to run if the condition is true.

Notice the different styles of brackets used in this statement: the round brackets or parentheses( ) are always placed around the condition while the curly brackets or braces { } are placed around the commands_to_execute.

In PowerShell the equality sign (=) is always used for assignment while -eq performs a comparison, so if you write IF (a = b) {echo "OK"} that will assign b to a and return false.

Examples

To compare two values, a string, a number or anything else:

$fruit = "orange"

If ($fruit -eq "orange") {'We found an orange'}

For this example we are just echoing a line of text, but the expression could be anything, copying a file, starting a service whatever you can think of.

To test more than one item, we can extend this with one or more Elseif() statements:

If ($fruit -eq "orange") {'We found an orange'}
ElseIf ($fruit -eq "apple") {'We found an apple'}
ElseIf ($fruit -eq "pear") {'We found an pear'}

Print the running services in green and stopped services in red:

get-service | foreach-object {  
  if ($_.status -eq "stopped") { write-host -f red $_.name $_.status }
  else { write-host -f green $_.name $_.status }
}

“You see things; and you say 'Why?' But I dream things that never were; and I say 'why not?' - George Bernard Shaw

Related PowerShell Cmdlets

ForEach - Loop through values in the pipeline.
Comparison operators - Full list.


 
Copyright © 1999-2024 SS64.com
Some rights reserved