Setting Defaults for Cmdlets

PowerShell v3 lets you, on a session-by-session basis, define your own defaults for any cmdlet.

Don Jones

October 11, 2011

1 Min Read
ITPro Today logo

First: Seemy caveats regarding PowerShell v3

PowerShell cmdlets often have defaults for specific parameters. In v3, however, you can pick what  they are! Now, this does not modify the default startup state of the shell. Rather, it's a command (or commands) that you must run each time you open a new shell window. Your defaults don't modify the cmdlets, so you have to re-define them in each new shell window you open. You could, of course, define your defaults in a profile script, which would have the effect of making them load each time you open a new shell window. 

The syntax is fairly straightforward: Create a hash table that uses special keys to define a cmdlet, a parameter, and a value for that parameter. For example, to make the -computerName parameter of Invoke-Command always point to "localhost," you'd run this:

$PSDefaultParameterValues = @{"Invoke-Command:ComputerName"="localhost"}


The trick is to assign that hash table to the built-in $PSDefaultParameterValues variable. You can make the hash table as large as you want to, specifying as many cmdlets and parameters as you like.

Adding a new cmdlet/parameter to the existing set of defaults is also easy:

$PSDefaultParameterValues += @{'Send-MailMessage:From'='[email protected]'}


That tells the Send-MailMessage cmdlet to use [email protected] for its -From parameter, while leaving my Invoke-Command:ComputerName default in place.

These are just defaults; you can always override them by manually specifying the parameter and providing it with a value. So you get awesome flexibility!

Like all variables, $PSDefaultParameterValues is scoped. That means you can create a new instance of it within a script, assign defaults, and those defaults will apply only to that script. When the script ends, the new $PSDefaultParameterValues goes away, and the shell reverts to using the globally-scoped one.

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like