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.
Comparison operators:
-eq = Equals
-match = Match (Not quite as definitive as equals)
-ne = Not equal
-notmatch = Does not match
-gt = Greater than
-ge = Greater than or equal to
-lt = Less than
-le = Less than or equal to
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