Consider this PowerShell function with a default parameter value:
function Greet($name = 'Guest') { Write-Output "Hello, $name!" }What will be the output of Greet when called without arguments?
function Greet($name = 'Guest') { Write-Output "Hello, $name!" } Greet
Think about what happens when you call a function without providing a value for a parameter that has a default.
The function Greet has a default value 'Guest' for the parameter $name. When called without arguments, it uses this default and outputs "Hello, Guest!".
Choose the correct syntax to define a function parameter $count with a default value of 5.
PowerShell uses the equals sign = to assign default values to parameters.
The correct syntax to assign a default value to a parameter in PowerShell is param([type]$paramName = defaultValue). Options A, B, and D use invalid syntax.
Look at this function:
function Show-Info {
param(
[Parameter(Mandatory=$true)]
[string]$name,
[int]$age = 30
)
Write-Output "$name is $age years old."
}
Show-InfoWhy does calling Show-Info without arguments cause an error?
function Show-Info { param( [Parameter(Mandatory=$true)] [string]$name, [int]$age = 30 ) Write-Output "$name is $age years old." } Show-Info
Check which parameters have default values and which do not.
The parameter $name has no default value, so it is required. Calling the function without providing $name causes an error. The parameter $age has a default value and is optional.
Given this PowerShell script:
function Calculate-Sum {
param(
[int]$a = 10,
[int]$b = 20
)
return $a + $b
}
$result1 = Calculate-Sum
$result2 = Calculate-Sum -a 5
$result3 = Calculate-Sum -b 15
$result4 = Calculate-Sum -a 3 -b 7
Write-Output "$result1,$result2,$result3,$result4"What will be the output?
function Calculate-Sum { param( [int]$a = 10, [int]$b = 20 ) return $a + $b } $result1 = Calculate-Sum $result2 = Calculate-Sum -a 5 $result3 = Calculate-Sum -b 15 $result4 = Calculate-Sum -a 3 -b 7 Write-Output "$result1,$result2,$result3,$result4"
Remember that parameters with default values use those defaults if not provided.
Calculations:
- $result1: defaults 10 + 20 = 30
- $result2: 5 + default 20 = 25
- $result3: default 10 + 15 = 25
- $result4: 3 + 7 = 10
Consider this function:
function Show-Message {
param(
[string]$text = 'Hello',
[string]$color = 'Blue'
)
Write-Output "$text in $color"
}And this splatting call:
$params = @{ text = 'Hi' }
Show-Message @paramsWhat will be the output and why?
function Show-Message { param( [string]$text = 'Hello', [string]$color = 'Blue' ) Write-Output "$text in $color" } $params = @{ text = 'Hi' } Show-Message @params
Think about how splatting passes only specified parameters and how defaults fill in missing ones.
Splatting passes only the text parameter with value 'Hi'. The color parameter is not passed, so PowerShell uses its default 'Blue'. The output is "Hi in Blue".