Tag Archives: PSDefaultParameterValues

Three Ways to Set $PSDefaultParameterValues Part II

In part one of this post, I indicated three different ways to populate the $PSDefaultParameterValues preference variable. The $PSDefaultParameterValues variable allow one to assign default values to the parameters of cmdlets and functions without ever needing to type them when they invoke the cmdlet or function. Here’s the two sets of examples from that post.

$PSDefaultParameterValues.Add('Get-Help:ShowWindow',$true)

$PSDefaultParameterValues = @{'Get-Help:ShowWindow' = $true}

$PSDefaultParameterValues['Get-Help:ShowWindow'] = $true


$PSDefaultParameterValues.Add('Out-Default:OutVariable','__')

$PSDefaultParameterValues = @{'Out-Default:OutVariable' = '__'}

$PSDefaultParameterValues['Out-Default:OutVariable'] = '__'

In the first section of the above example, we set the ShowWindow parameter of Get-Help to $true. Now, whenever I use Get-Help, it will always include the ShowWindow parameter, and I don’t have to type a thing. Keep in mind, if it’s not clear, that the first three commands all do the same thing. You’d only need to run one of them. The same goes for the second section of the above example.

So, I recently wrote a function at work. It’s another PowerShell random password generator, as if the world needed one more. In my version, there’s a CharacterType parameter that can accept one or more of four predefined values: Lowercase, Number, Symbol, and Uppercase. These values can be used alone, or in combination with each other. As I have a coworker that didn’t want symbols, I obliged by adding this character type feature. I should mention that if the CharacterType parameter isn’t included at all, that it will default to use all four character types. As it should.

Now, my coworker doesn’t have to type the below command over and over in order to include three of the four possible values, every time.

PS > New-RandomPassword -CharacterType Lowercase,Number,Uppercase

That’s when it dawned on me. I’m not sure I’ve ever used the $PSDefaultParameterValues preference variable with multiple parameter values. It’s up there, but to review, the function is New-RandomPassword, and the parameter where we want default values is called CharacterType. The default values we always want included are Lowercase, Number, and Uppercase. As you’d expect, we’re avoiding symbols in our random passwords for this example.

$PSDefaultParameterValues = @{'New-RandomPassword:CharacterType'='Number','Uppercase','Lowercase'}

$PSDefaultParameterValues['New-RandomPassword:CharacterType'] = 'Number','Uppercase','Lowercase'

$PSDefaultParameterValues.Add('New-RandomPassword:CharacterType',@('Number','Uppercase','Lowercase'))

Although you’d only need to run one of them, each of the above examples will modify $PSDefaultParameterValues the identical way.

PS > $PSDefaultParameterValues | Format-Table -AutoSize

Name                             Value
----                             -----
New-RandomPassword:CharacterType {Number, Uppercase, Lowercase}

Now, whenever New-RandomPassword is invoked (on a system where this entry is a part of $PSDefaultParameterValues, obviously), it’ll include those values, for that parameter, without the need to actually type the parameter name and the values — neat. As of now, I can say I’ve include multiple values for a single parameter using the $PSDefaultParameterValues variable. You too, or at least you can say you know it’s an option.

Three Ways to Set $PSDefaultParameterValues

Update: When you’re done here, read Part II.

Although we’ve discussed the $PSDefaultParameterValues before, I wanted to do a quick recap. I need one place that shows the various ways to set this variable. That’s what this post will do for me, and perhaps you too.

First, however, let’s remind everyone what the $PSDefaultParameterValues variable does for us. It allows us to set a custom, default value for a function or cmdlet’s parameter. One of the examples I mentioned before, in one of the three posts I’ve written about $PSDefaultParameterValues (1 | 2 | 3), used Get-Help.

This cmdlet includes a ShowWindow switch parameter that will open the full help inside its own GUI window. I tend to use this option a great deal to keep my ConsoleHost clean. In order to keep this post short, I’m just going to write the three ways in which I’m aware that we can set this variable.

$PSDefaultParameterValues.Add('Get-Help:ShowWindow',$true)

$PSDefaultParameterValues = @{'Get-Help:ShowWindow' = $true}

$PSDefaultParameterValues['Get-Help:ShowWindow'] = $true

Oh, Lee Holmes posted a welcome PSDefaultParameterValues addition on Twitter recently. I’ve included that addition below using the three above options, as well. Unlike his example, I moved from three underscores to two. You’ll see what I mean below if you haven’t already read the Tweet.

With this example in place, the results of all the commands entered will end up in the $__ variable. Again, that’s two underscores. Run a Get-ADUser command, for instance, and you’ll get the results both on the screen and in the $__ variable up until you run another command that can make use of the OutVariable common parameter.

$PSDefaultParameterValues.Add('Out-Default:OutVariable','__')

$PSDefaultParameterValues = @{'Out-Default:OutVariable' = '__'}

$PSDefaultParameterValues['Out-Default:OutVariable'] = '__'

PSMonday #25: October 17, 2016

Topic: $PSDefaultParameterValues II

Notice: This post is a part of the PowerShell Monday series — a group of quick and easy to read mini lessons that briefly cover beginning and intermediate PowerShell topics. As a PowerShell enthusiast, this seemed like a beneficial way to ensure those around me at work were consistently learning new things about Windows PowerShell. At some point, I decided I would share these posts here, as well. Here’s the PowerShell Monday Table of Contents.

To recap last week, the $PSDefaultParameterValues preference variable stores default parameter names and corresponding values for cmdlets and functions. This means we can use cmdlets and functions with modified parameters, without the need to type in the names and values each time.

Last week we used the Add and Remove methods. This week, we’ll use standard hash table syntax, since that’s all this variable holds. Hash tables were first introduced back on May 30, 2016 when we first discussed creating and splatting a parameter hash table. A hash table contains key-value pairs.

Let’s add a new entry to our empty $PSDefaultParameterValues variable.

$PSDefaultParameterValues = @{'Get-Help:ShowWindow'=$true}
$PSDefaultParameterValues

Name                           Value
----                           -----
Get-Help:ShowWindow            True

Just as we did last, when we enter the variable name after it’s populated, it’ll return the results in the standard, hash table output to include the Name and Value properties.

With the ShowWindow parameter name set to a value of True, Get-Help will always show the full help inside a GUI window and not pollute the ConsoleHost or ISE (PowerShell 3.0 and greater only), without the need to actually type the switch parameter -ShowWindow.

If your variable is already holding a value, be sure to use the += assignment operator instead of the = assignment operator, or you’ll overwrite what was already being stored in the variable.

On an entry after the first one, use this:

$PSDefaultParameterValues += @{'Get*:Verbose'=$true}

Not this:

$PSDefaultParameterValues = @{'Get*:Verbose'=$true}

Notice that in the above examples we’ve used a wildcard character. If this is added to your $PSDefaultParameterValues, then all Get-* cmdlets and functions will include the Verbose parameter.

Give a Parameter a Default Value (Part III)

Part II: http://tommymaynard.com/quick-learn-give-a-parameter-a-default-value-part-ii-2015

Didn’t know I’d be back for a third installment of this topic, but the $PSDefaultParameterValues variable is still such a huge convenience. While punching out commands today, I had a thought: Can $PSDefaultParameterValues be a bit more dynamic?

I’m not going to fully introduce the $PSDefaultParameterValues again, but I’ll leave a quick explanation. This hash table allows us to instruct cmdlets and functions to use a default value for one of their parameters. Here’s a couple examples borrowed from the first two $PSDefaultParameterValues posts. To read the first two posts, follow the links at the bottom of this post. Both of these examples do the same thing, outside of the fact they’re written for different cmdlets.

$PSDefaultParameterValues.Add('Test-Connection:Count','1')
$PSDefaultParameterValues = @{'Get-Help:ShowWindow' = $true}

After our variable is set, anytime I use the Test-Connection cmdlet, it will include the -Count parameter with the parameter value of 1. Additionally, when I use Get-Help, it will always include the -ShowWindow parameter, without the need to enter it myself. The examples show how to set the variable both by using the Add method, and as a hash table — which is really all the variable is anyway.

I had a recent need to ensure the -Server parameter value on the Get-ADPrincipalGroupMembership cmdlet used the PDC Emulator. If you see the error: “The operation being requested was not performed because the user has not been authenticated, then you may need to ensure you’re using the PDCE when using this cmdlet, too. Anyway, I didn’t want to hard code the PDCE value in $PSDefaultParameterValues, so I tried something new, and you’re reading this today, because it worked. Here’s how I updated the $PSDefaultParameterValues variable to dynamically obtain the value it should use.

$PSDefaultParameterValues.Add('Get-ADPrincipalGroupMembership:Server',"$((Get-ADDomain).PDCEmulator)")
$PSDefaultParameterValues | Format-Table -AutoSize

Name                                  Value
----                                  -----
Get-ADPrincipalGroupMembership:Server DC01.mydomain.com

Now, whenever I run the Get-ADPrincipalGroupMembership cmdlet (inside the PowerShell session where the $PSDefaultParameterValues has been set), it’ll include the -Server parameter and the value of the PDCE — which ever server that is, and without the need to hard code its name. So yeah, we can use dynamic content in $PSDefaultParameterValues.

Part I: http://tommymaynard.com/quick-learn-give-a-parameter-a-default-value-2015
Part II: http://tommymaynard.com/quick-learn-give-a-parameter-a-default-value-part-ii-2015

Update: A buddy at work alerted me to the fact that pointing to the PDCE is no longer necessary for the Get-ADPrincipalGroupMembership cmdlet. Thanks, Logan!

Give a Parameter a Default Value (Part II)

Part I: http://tommymaynard.com/quick-learn-give-a-parameter-a-default-value-2015
Part III: http://tommymaynard.com/quick-learn-give-a-parameter-a-default-value-part-iii-2016

An old co-worker and friend contacted me last week. We hadn’t chatted since the last time I was interviewing for a job — a job I have now (well, pretty close anyway). I remember telling him I wanted a job that allowed me to work with Windows PowerShell. While he probably wasn’t surprised to hear this job did just that, he might have been, to hear I had started this site — a site using my name, and all about PowerShell. It’s a pretty serious commitment to associate your name with a technology, and continue to provide new content.

He mentioned to me that he wasn’t aware of the $PSDefaultParameterValues preference variable until he read this post. No joke, but it’s exciting to know that something I wrote was helpful for him. You see, this isn’t your average intelligence IT Pro, no, this is walking, talking IT genius. You know the kind — one of the ones you’d hire first, if you opened your own consulting business. In fact, during that same first chat, I discovered that he spoke at the Microsoft Higher-Education Conference in October 2014. He’s definitely doing something right.

As last weekend passed, I occasionally thought about that $PSDefaultParameterValues post and decided I should add something more to it, especially since I highlighted what I would consider to be the less used approach for populating this variable. First off, for those that haven’t read the previous post, the $PSDefaultParameterValues variable allows you to specify a default value for a cmdlet’s, or function’s, parameter(s).

For example, if I wanted the Get-Help cmdlet to always include the -ShowWindow parameter, then I can add that default value to the cmdlet like so:

PS C:\> $PSDefaultParameterValues
PS C:\> # Proof the variable is empty.
PS C:\> $PSDefaultParameterValues.Add('Get-Help:ShowWindow',$true)
PS C:\> $PSDefaultParameterValues

Name                           Value
----                           -----
Get-Help:ShowWindow            True

With this value set, every time we use the Get-Help cmdlet, it will include the -ShowWindow parameter, even though I don’t specifically enter it at the time the command is run. In the previous example, we use the .Add() method to add a key-value pair; however, I suspect that most people will actually be more likely to use a hash table to add the cmdlet and parameter, and its new, default parameter value. Here’s the same example as above using the hash table option.

PS C:\> $PSDefaultParameterValue
PS C:\> # Proof the variable is empty.
PS C:\> $PSDefaultParameterValues = @{'Get-Help:ShowWindow' = $true}
PS C:\> $PSDefaultParameterValues

Name                           Value
----                           -----
Get-Help:ShowWindow            True

Now for the reason I led with with .Add() method: If you use the hash table option above, and the variable is already populated, then it’s going to overwrite the value it’s already storing, unless we use the += assignment operator. Follow along in the next few examples under the assumption that $PSDefaultParameterValues, is already populated from the previous example.

PS C:\> $PSDefaultParameterValues

Name                           Value
----                           -----
Get-Help:ShowWindow            True

PS C:\> $PSDefaultParameterValues = @{'Get-ADUser:Server' = 'MyClosestDC'}
PS C:\> $PSDefaultParameterValues

Name                           Value
----                           -----
Get-ADUser:Server              MyClosestDC

In the example above, using the = assignment operator overwrote our Get-Help ShowWindow key-value pair, as it would with any populated variable. The idea here is that we either need to assign all the parameter default values at once (when using a hash table), or use the += assignment operator to append other key-value pairs. Here’s both ways:

PS C:\> $PSDefaultParameterValues
PS C:\> # Proof the variable is empty.
PS C:\> $PSDefaultParameterValues = @{'Get-Help:ShowWindow' = $true;'Get-ADUser:Server' = 'MyClosestDC'}
PS C:\> $PSDefaultParameterValues

Name                           Value
----                           -----
Get-ADUser:Server              MyClosestDC
Get-Help:ShowWindow            True

PS C:\> $PSDefaultParameterValues = $null
PS C:\> $PSDefaultParameterValues
PS C:\> # Proof the variable is empty.
PS C:\> $PSDefaultParameterValues = @{'Get-Help:ShowWindow' = $true}
PS C:\> $PSDefaultParameterValues += @{'Get-ADUser:Server' = 'MyClosestDC'}
PS C:\> $PSDefaultParameterValues

Name                           Value
----                           -----
Get-ADUser:Server              MyClosestDC
Get-Help:ShowWindow            True

That’s all there is to it. If you’re going to use a hash table and assign values to your $PSDefaultParameterValues at different times, then be sure to use the correct assignment operator, or use the .Add() method — it’s up to you. For me, I populate this variable in my profile, so overwriting it, is something in which I’m not concerned. Thanks for reading!

Give a Parameter a Default Value

Part II: http://tommymaynard.com/quick-learn-give-a-parameter-a-default-value-part-ii-2015/

If you’re into Windows PowerShell, then you probably think a little like me. You want to do things fast, and efficiently. There’s a reason we pound out commands and write scripts: we want to make the most of our time, and PowerShell let’s us do that. With that in mind, I decided I should modify a cmdlet I often use, so that using it takes less time, by default.

The Test-Connection cmdlet does for us what ping always has. It sends ICMP request packets to a remote computer or device. If the remote computer or device sends us a reply, then we know the device is up. It should be stated, that ICMP replies can be restricted so that a computer or device that is up, may not reply. Although I’ve opted to use Test-Connection for my example, this concept can be used with any number of other cmdlets and their parameters.

Let’s start by taking a look at the default output of the Test-Connection cmdlet. By default, Test-Connection will ping a given computer four times. If I were checking for latency, four replies would probably be better than one, but because I just want to know if the computer is up or down, a single reply is suitable.

PS C:\> Test-Connection -ComputerName bing.com

Source        Destination     IPV4Address      IPV6Address                              Bytes    Time(ms)
------        -----------     -----------      -----------                              -----    --------
TOMMYMAYNA... bing.com        204.79.197.200                                            32       14
TOMMYMAYNA... bing.com        204.79.197.200                                            32       13
TOMMYMAYNA... bing.com        204.79.197.200                                            32       14
TOMMYMAYNA... bing.com        204.79.197.200                                            32       13

This cmdlet includes a -Count parameter, and so I could have used that, as -Count 1, so that my computer only sent a single packet. But remember, I want be fast and efficient — I don’t want type more to see less. I want to type the same and make things faster. To accomplish this, what I’ll do is change the default behavior of this command to only send one packet. These means I’ll need to make use of the $PSDefaultParameterValues variable.

The $PSDefaultParameterValues variable stores any modifications to the default values of any of our cmdlet’s parameters. Since I don’t have any modified default values, the variable has nothing to return.

PS C:\> $PSDefaultParameterValues
PS C:\>

In the example below, we’ll use the Add() method to add a key/value pair to the variable. The keys are anything in the Name property, and the values are anything in the Value property. There is a one-to-one ratio between keys and values. These are also referred to as hash tables, associative arrays, or a dictionary object.

After we’ve added our key/value pair, we’ll try Test-Connection again, as we did in the first example.

PS C:\> $PSDefaultParameterValues.Add('Test-Connection:Count','1')
PS C:\> $PSDefaultParameterValues

Name                           Value
----                           -----
Test-Connection:Count          1

PS C:\> Test-Connection -ComputerName bing.com

Source        Destination     IPV4Address      IPV6Address                              Bytes    Time(ms)
------        -----------     -----------      -----------                              -----    --------
TOMMYMAYNA... bing.com        204.79.197.200                                            32       13

PS C:\>

As we can see, Test-Connection will now only ping a computer one time by default. Now, what happens when I do want to test for latency? I can use the -Count parameter and supply whatever number I want, so long as it’s 1 through 2147483647. Using zero or less, or 2147483648 will not work. I know, I tried.

You can read more information on the about_Parameters_Default_Values page here: https://technet.microsoft.com/en-us/library/hh847819.aspx.