I was working on a script to copy a single file to multiple destinations, and I needed to specify multiple credentials (for the source and the destination, perhaps they’re different).  Of course, they could be the same.  In either case, I didn’t want to specify extra parameters if I could avoid it.

So, with that in mind, I wanted to do the following:

  • If the credentials are the same for the source and destination, pass a single credential via the -Credential option
  • If the credentials are different, pass -SourceCredential and -DestinationCredential options

That’s easy enough, but the neat trick that I found was that parameter sets will still allow you to set defaults even if you aren’t using them.  For example:

[Parameter(ParameterSetName = "SingleCredential", Mandatory = $true)][PSCredential]$Credential,
[Parameter(ParameterSetName = "DualCredential", Mandatory = $true)][PSCredential]$SourceCredential = $Credential,
[Parameter(ParameterSetName = "DualCredential", Mandatory = $true)][PSCredential]$DestinationCredential = $Credential

So, with this in the Param() block, the following happens:

  • If you pass the -Credential parameter, you can refer to $SourceCredential and $DestinationCredential later in the script – both will have the same credential assigned to them.
  • If you try to pass only one of -SourceCredential or -DestinationCredential, you will be prompted for the option you forgot, like you’d expect (since they’re both required).

It might not seem like much, but it’s a slick little way of handling a unique situation that I ran into.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.