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?
[CmdletBinding()] must come before param(). Only options A, B, and D do this correctly; C is wrong.
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.
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].
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
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
Master "Functions" in PowerShell
9 interactive learning modes - each teaches the same concept differently