0
0
PowerShellscripting~10 mins

Advanced functions (CmdletBinding) in PowerShell - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare an advanced function with CmdletBinding.

PowerShell
function Get-Greeting {
    [[1]()]
    param ()
    "Hello, World!"
}
Drag options to blanks, or click blank then click option'
AAlias
BParameter
COutputType
DCmdletBinding
Attempts:
3 left
💡 Hint
Common Mistakes
Using Parameter instead of CmdletBinding.
Forgetting the parentheses after CmdletBinding.
Placing CmdletBinding inside the param block.
2fill in blank
medium

Complete the code to define a mandatory string parameter in an advanced function.

PowerShell
function Get-Greeting {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=[1])]
        [string]$Name
    )
    "Hello, $Name!"
}
Drag options to blanks, or click blank then click option'
A$true
B$false
CTrue
DFalse
Attempts:
3 left
💡 Hint
Common Mistakes
Using True or False without the $ sign.
Setting Mandatory to $false when the parameter should be required.
3fill in blank
hard

Fix the error in the advanced function to correctly support pipeline input by property name.

PowerShell
function Get-Greeting {
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipelineByPropertyName=[1])]
        [string]$Name
    )
    process {
        "Hello, $Name!"
    }
}
Drag options to blanks, or click blank then click option'
A$false
BTrue
C$true
DFalse
Attempts:
3 left
💡 Hint
Common Mistakes
Using True or False without the $ sign.
Setting ValueFromPipelineByPropertyName to $false disables pipeline input.
4fill in blank
hard

Fill both blanks to add a switch parameter and output a message when it is used.

PowerShell
function Get-Greeting {
    [CmdletBinding()]
    param (
        [switch]$VerboseMode
    )
    begin {
        if ([1]) {
            Write-Verbose "[2] mode is on."
        }
    }
    process {
        "Hello!"
    }
}
Drag options to blanks, or click blank then click option'
AVerboseMode
BVerbose
C$VerboseMode
D$Verbose
Attempts:
3 left
💡 Hint
Common Mistakes
Using variable names without $ in the if condition.
Confusing Verbose and VerboseMode parameter names.
5fill in blank
hard

Fill all three blanks to define an advanced function with a string parameter, pipeline input, and output type.

PowerShell
function Get-Greeting {
    [[1]()]
    [OutputType([3])]
    param (
        [Parameter(ValueFromPipelineByPropertyName=[2])]
        [string]$Name
    )
    process {
        "Hello, $Name!"
    }
}
Drag options to blanks, or click blank then click option'
ACmdletBinding
B$true
C[string]
DParameter
Attempts:
3 left
💡 Hint
Common Mistakes
Using Parameter instead of CmdletBinding.
Using False instead of $true for pipeline input.
Not specifying output type as [string].