Bird
0
0

Which code snippet correctly implements this behavior?

hard📝 Application Q15 of 15
PowerShell - Scripting Best Practices
You want to write a PowerShell script that shows detailed debug messages only when debugging is enabled, and verbose messages only when verbose is enabled. Which code snippet correctly implements this behavior?
A<pre>$DebugPreference = 'Continue' Write-Output "Normal output" Write-Debug "Debug info" Write-Verbose "Verbose info"</pre>
B<pre>Write-Debug "Debug info" Write-Verbose "Verbose info" Write-Output "Normal output"</pre>
C<pre>if ($DebugPreference -eq 'SilentlyContinue') { Write-Debug "Debug info" } if ($VerbosePreference -eq 'SilentlyContinue') { Write-Verbose "Verbose info" } Write-Output "Normal output"</pre>
D<pre>Write-Debug "Debug info" Write-Verbose "Verbose info" Write-Output "Normal output" Set-Variable -Name DebugPreference -Value 'Continue'</pre>
Step-by-Step Solution
Solution:
  1. Step 1: Understand default behavior of Write-Debug and Write-Verbose

    These commands automatically show messages only if debugging or verbose is enabled by running script with -Debug or -Verbose.
  2. Step 2: Analyze code snippets

    Write-Debug "Debug info"
    Write-Verbose "Verbose info"
    Write-Output "Normal output"
    uses both commands directly, which is correct.
    $DebugPreference = 'Continue'
    Write-Output "Normal output"
    Write-Debug "Debug info"
    Write-Verbose "Verbose info"
    sets $DebugPreference to 'Continue' first, forcing debug messages to always show even without -Debug.
    if ($DebugPreference -eq 'SilentlyContinue') { Write-Debug "Debug info" }
    if ($VerbosePreference -eq 'SilentlyContinue') { Write-Verbose "Verbose info" }
    Write-Output "Normal output"
    checks for 'SilentlyContinue', showing messages when NOT enabled.
    Write-Debug "Debug info"
    Write-Verbose "Verbose info"
    Write-Output "Normal output"
    Set-Variable -Name DebugPreference -Value 'Continue'
    sets DebugPreference after messages, so ineffective.
  3. Final Answer:

    Write-Debug "Debug info" Write-Verbose "Verbose info" Write-Output "Normal output" -> Option B
  4. Quick Check:

    Write-Debug and Write-Verbose auto-check flags [OK]
Quick Trick: Use Write-Debug and Write-Verbose directly; flags control output [OK]
Common Mistakes:
  • Forcing preference to 'Continue' unconditionally
  • Using incorrect condition like 'SilentlyContinue' in checks
  • Setting preferences after output commands

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PowerShell Quizzes