0
0
PowerShellscripting~5 mins

Default parameter values in PowerShell

Choose your learning style9 modes available
Introduction
Default parameter values let you set a fallback value for a function's input. This means the function still works even if you don't give it all the information.
When you want a function to work with common settings without needing extra input.
When you want to avoid errors if a user forgets to provide a parameter.
When you want to make your script easier to use by providing sensible defaults.
Syntax
PowerShell
function FunctionName {
  param(
    [type]$ParameterName = DefaultValue
  )
  # Function code here
}
You set the default value by using '=' after the parameter name.
If the caller does not provide a value, the default is used automatically.
Examples
This function says hello. If you don't give a name, it uses "Friend".
PowerShell
function Greet {
  param(
    [string]$Name = "Friend"
  )
  Write-Output "Hello, $Name!"
}

Greet
Greet -Name "Alice"
This function adds two numbers. If you don't give numbers, it adds 5 and 10.
PowerShell
function Add-Numbers {
  param(
    [int]$a = 5,
    [int]$b = 10
  )
  return ($a + $b)
}

Add-Numbers
Add-Numbers -a 3 -b 7
Sample Program
This script defines a function that shows a message. If no message is given, it shows "Hello, World!".
PowerShell
function Show-Message {
  param(
    [string]$Message = "Hello, World!"
  )
  Write-Output $Message
}

Show-Message
Show-Message -Message "PowerShell is fun!"
OutputSuccess
Important Notes
Default values can be any valid PowerShell expression.
You can mix parameters with and without default values, but parameters with defaults should come last.
Using default values makes your functions more flexible and user-friendly.
Summary
Default parameter values provide fallback inputs for functions.
They help avoid errors when parameters are missing.
They make scripts easier to use by setting common defaults.