Setting Defaults for Cmdlets

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'='admin@company.com'}
That tells the Send-MailMessage cmdlet to use admin@company.com 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.

Please or Register to post comments.

What's PowerShell with a Purpose Blog?

Don Jones demystifies Windows PowerShell.

Blog Archive

Sponsored Introduction Continue on to (or wait seconds) ×