Using Default Parameters

by Jul 5, 2018

If you find yourself always using the same parameter values over again, try using PowerShell default parameters. Here is how:

# hash table
# Key =
# Cmdlet:Parameter
# Value = 
# Default value for parameter
# * (Wildcard) can be used

$PSDefaultParameterValues = @{ 
'Stop-Process:ErrorAction' = 'SilentlyContinue' 
'*:ComputerName' = 'DC-01'
'Get-*:Path' = 'c:\windows'

At its core, there is a hash table called $PSDefaultParametersValues. By default, it does not exist or is empty. If you’d like to reset default parameters to their defaults, run this:

PS> $PSDefaultParameterValues = $null 

The hash table key is a combination of cmdlet name and parameter name, separated by a ***. Wildcards are allowed. The hash table value is the default parameter value.

In the example above:

  • Stop-Process would always use “SilentlyContinue” for -ErrorAction.
  • Any cmdlet with the -ComputerName parameter would use “DC-01”.
  • Any cmdlet with the “Get” verb and the -Path parameter would use “C:\windows” by default

Default parameters can be handy but also tricky. You should never define them in your profile script because chances are you forget about them, and next week wonder why your cmdlets behave unexpectedly.

Also note that default parameters work only for cmdlets and advanced functions. They do not work for simple functions:

function Start-SimpleFunction

    "ID = $ID"

function Start-AdvancedFunction

    "ID = $ID"


$PSDefaultParameterValues = @{
    "Start-*Function:ID" = 12345

Here is the result:

PS> Start-SimpleFunction
ID = 100

PS> Start-AdvancedFunction
ID = 12345


Twitter This Tip! ReTweet this Tip!