Boost your confidence for the CompTIA PenTest+ Exam. Train with a quiz featuring flashcards and detailed questions, each offering hints and comprehensive explanations. Prepare thoroughly for your test!

Each practice test/flash card set has 50 randomly selected questions from a bank of over 500. You'll get a new set of questions each time!

Practice this question and more.


In PowerShell, what is the correct form of an if statement?

  1. if ($my_var = 1) { Write-Host "Correct." }

  2. if [$my_var -eq 1] { Write-Host "Correct." }

  3. $my_var = 1; if ($my_var -eq 1) { Write-Host "Correct." }

  4. if ($my_var -eq 1) { Write-Host "Correct." } else { Write-Host "Incorrect." }

The correct answer is: if ($my_var -eq 1) { Write-Host "Correct." } else { Write-Host "Incorrect." }

The selection is accurate because it correctly follows the syntax and logical formatting for an if statement in PowerShell. In PowerShell, the if statement begins with the keyword 'if', followed by a condition within parentheses. The use of '-eq' is the operator used in PowerShell to check for equality, making this a proper conditional check. After the condition, the block of code that executes if the condition is true is enclosed in curly braces. This option also includes an additional 'else' statement, which allows for handling an alternative case when the condition is false. This structure is important in programming, as it accounts for both possible outcomes of the comparison, providing clear paths for execution. The inclusion of 'else' makes the statement not only correct but completes it by ensuring all logical scenarios are addressed. The other choices fail to follow proper syntax or logical constructs within PowerShell. They either use incorrect operators or structure. For instance, using a single '=' assigns a value rather than testing it, and square brackets are not used for conditions in PowerShell. Therefore, the chosen statement exemplifies a well-formed if statement in PowerShell.