Default Parameters in PowerShell

Image Description

Daily PowerShell #7

Scripting Daily PowerShell

October 24, 2021

quote Discuss this Article

Default parameter values allow you to assign static and dynamic default values to cmdlet parameters within a PowerShell session. This post will take you through some examples of using the $PSDefaultParameterValues hashtable.

Setting Static Default Parameters

The $PSDefaultParameterValues hashtable can be defined to set static parameter values. The key in the hashtable is the name of the cmdlet and parameter you wish to set followed by the value.

$PSDefaultParameterValues = @{
    "Write-Host:Object" = "Hello, World!"
}
Write-Host

Setting Dynamic Default Parameters

In addition to setting a static value, you can also assign a script block that will be invoked to set the default value.

$PSDefaultParameterValues = @{
    "Write-Host:Object" = "Hello from $($PSversionTable.OS)!"
}
Write-Host

Editing Default Parameter Values

You can adjust default parameter values at runtime by using standard hashtable features such as indices and the Add and Remove methods.

$PSDefaultParameterValues = @{
    "Write-Host:Object" = "Hello, world!"
}
$PSDefaultParameterValues["Write-Host:Object"] = "Hello, Universe!"
Write-Host

$PSDefaultParameterValues.Add("Write-Host:ForegroundColor", "Red")
Write-Host


$PSDefaultParameterValues.Remove("Write-Host:ForegroundColor")
Write-Host

Disable Default Parameter Values

To disable default parameter values, add a Disabled key and set it to $true.

$PSDefaultParameterValues = @{
    "Write-Host:Object" = "Hello, world!"
}
$PSDefaultParameterValues.Add("Disabled", $true)
Write-Host