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.

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-2014
Some rights reserved