if Statement
noun
say it: “IF STAYT-ment” /ˈɪf ˈsteɪtmənt/
A part of a script that runs some commands only when a test is true, and can run other commands when it's false.
What is an if statement in PowerShell?
An if statement runs the commands in its braces only when the test in its parentheses is True. elseif adds another test and else catches everything left; PowerShell tries them from the top and runs only the first block whose test is True.
$changed = @('essay.txt', 'empty-draft.txt')
$Preview = $true
if ($changed.Count -eq 0) { 'Nothing changed, so nothing was copied.' }
elseif ($Preview) { "Preview only. Files that would be copied: $($changed.Count)." }
else { "Files copied: $($changed.Count)." }
# Preview only. Files that would be copied: 2.
In a sentence
- “Sam's backup uses an if statement to skip the copy when nothing changed.”
- “The if statement stops the script with a plain message when the folder name is misspelled.”
Level: Apprentice · More PowerShell terms at this level
Updated