Bird
0
0

You want to create an advanced function that accepts a switch parameter -Verbose to show extra messages only when the switch is used. Which code snippet correctly implements this behavior?

hard📝 Application Q15 of 15
PowerShell - Functions
You want to create an advanced function that accepts a switch parameter -Verbose to show extra messages only when the switch is used. Which code snippet correctly implements this behavior?
Afunction Show-Info { [CmdletBinding()] param() if ($Verbose) { Write-Output 'Verbose mode ON' } else { Write-Output 'Normal mode' } }
Bfunction Show-Info { [CmdletBinding()] param([switch]$Verbose) if ($PSBoundParameters.ContainsKey('Verbose')) { Write-Output 'Verbose mode ON' } else { Write-Output 'Normal mode' } }
Cfunction Show-Info { param([switch]$Verbose) [CmdletBinding()] if ($Verbose) { Write-Output 'Verbose mode ON' } else { Write-Output 'Normal mode' } }
Dfunction Show-Info { [CmdletBinding()] param([bool]$Verbose) if ($Verbose -eq $true) { Write-Output 'Verbose mode ON' } else { Write-Output 'Normal mode' } }
Step-by-Step Solution
Solution:
  1. Step 1: Confirm CmdletBinding and param order

    [CmdletBinding()] must come before param(). Only options A, B, and D do this correctly; C is wrong.
  2. Step 2: Check switch parameter usage

    Switch parameters are declared as [switch]$Verbose. To detect if switch was used, check $PSBoundParameters.ContainsKey('Verbose') or $Verbose directly. function Show-Info { [CmdletBinding()] param([switch]$Verbose) if ($PSBoundParameters.ContainsKey('Verbose')) { Write-Output 'Verbose mode ON' } else { Write-Output 'Normal mode' } } uses $PSBoundParameters which is reliable.
  3. Step 3: Evaluate parameter type

    function Show-Info { [CmdletBinding()] param([bool]$Verbose) if ($Verbose -eq $true) { Write-Output 'Verbose mode ON' } else { Write-Output 'Normal mode' } } uses [bool] which is not the recommended type for switches; switches are special and should use [switch].
  4. Final Answer:

    function Show-Info { [CmdletBinding()] param([switch]$Verbose) if ($PSBoundParameters.ContainsKey('Verbose')) { Write-Output 'Verbose mode ON' } else { Write-Output 'Normal mode' } } -> Option B
  5. Quick Check:

    CmdletBinding before param, switch param, check $PSBoundParameters = A [OK]
Quick Trick: Use [switch] param and check $PSBoundParameters['Verbose'] [OK]
Common Mistakes:
  • Placing CmdletBinding after param
  • Using [bool] instead of [switch]
  • Checking switch with just $Verbose without $PSBoundParameters

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PowerShell Quizzes