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.

Examples

Replace the text in the variable $MyDemoVar:

PS C:\> if ($MyDemoVar -like "*SS64*") {$MyDemoVar -replace "SS64", "Demonstration Example"}

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

PS C:\> 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:

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


Copyright © SS64.com 1999-2017
Some rights reserved