Conditionally perform a command.

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

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

              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.


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 PowerShell Commands:

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

Copyright © SS64.com 1999-2019
Some rights reserved