Bird
0
0

You want to create a script that uses a feature exclusive to PowerShell 7+, but it should not fail on PowerShell 5.1. Which method is the best practice to conditionally run the feature?

hard📝 Application Q8 of 15
PowerShell - Basics and Environment
You want to create a script that uses a feature exclusive to PowerShell 7+, but it should not fail on PowerShell 5.1. Which method is the best practice to conditionally run the feature?
ACheck if $PSVersionTable.PSEdition equals 'Desktop' before running the feature
BUse try-catch to run the feature and ignore errors if it fails
CCheck if $PSVersionTable.PSVersion.Major is greater than or equal to 7 before executing the feature
DRun the feature unconditionally and expect it to work on both versions
Step-by-Step Solution
Solution:
  1. Step 1: Identify version-specific features

    Features exclusive to PowerShell 7+ require a version check to avoid errors in 5.1.
  2. Step 2: Use $PSVersionTable.PSVersion.Major

    This property reliably indicates the major version number, allowing conditional execution.
  3. Step 3: Avoid unreliable checks

    Checking PSEdition or relying on try-catch is less precise or inefficient.
  4. Final Answer:

    Check if $PSVersionTable.PSVersion.Major is greater than or equal to 7 before executing the feature -> Option C
  5. Quick Check:

    Use version number checks for conditional feature use [OK]
Quick Trick: Use $PSVersionTable.PSVersion.Major for version checks [OK]
Common Mistakes:
  • Using PSEdition to determine feature availability
  • Ignoring version checks and causing script failures
  • Relying solely on try-catch for compatibility

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PowerShell Quizzes