I'm trying to write a failure simple script utilizing parameter sets to simplify input and validation. I'd like the script to look like this:
.\zipandrotate.ps1 -Zip [-AllButDays <int>] -Rotate [-MaxRetentionDays <int>]
-Zip
and therefore -AllButDays
are optional as is -Rotate
and -MaxRetentionDays
.
I have tried setting a default parameter set to zip but that did not work. I would like it to allow the execution to be: just zip, just rotate or both zip and rotate.
[CmdletBinding(DefaultParameterSetBame="zip")]
param(
[Parameter(Mandatory=$false, ParameterSetName="zip")]
[Switch]$Zip,
[Parameter(Mandatory=$true, ParameterSetName="rotate")]
[Switch]$Rotate,
[Parameter(ParameterSetName="zip", Mandatory=$true)]
[int]$AllButDays,
[Parameter(ParameterSetName="rotate", Mandatory=$false)]
[int]$MaxRetentionDays
)
I get the following error in PowerShell 5 (Windows 10) and PowerShell 4 (Windows 7):
PS C:\> .\zipandrotate.ps1 -Zip -AllButDays 2 -Rotate -MaxRetentionDays 2 C:\zipandrotate.ps1 : Parameter set cannot be resolved using the specified named parameters. At line:1 char:1 + .\zipandrotate.ps1 -Zip -AllButDays 2 -Rotate -MaxRetentionDays 2 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [zipandrotate.ps1], ParameterBindingException + FullyQualifiedErrorId : AmbiguousParameterSet,zipandrotate.ps1
Running the command three different ways tells me problem is in trying to use -Zip
and -Rotate
at the same time.
Works:
.\zipandrotate.ps1 -zip -allbutdays 2
.\zipandrotate.ps1 -rotate -maxretentiondays 90
Doesn't work:
.\zipandrotate.ps1 -zip -allbutdays 2 -rotate -maxretentiondays 90
So there are 4 paths I see my script going:
Allowed: Just zip, Just Rotate, Both
Not Allowed: None
Any advice on how I get there? Adding a third parameter set reversed the situation. Only -Zip
and -Rotate
worked; individual uses no longer had any unique cases to determine which parameter set they were. Is there a way to get the functionality I want to remove the need for an extra parameter to run -Zip
or -Rotate
alone?