I am putting together a set of tools for internal account management. This particular cmdlet will prep an account for a transfer out, which includes an option to remove or retain their groups. My Param statement has become quite lengthy and has ended up with 6 parameter sets to cover every scenario. All combinations of parameters are working except for one. Here is my code:
function Move-AccountOut {
[CmdletBinding(DefaultParameterSetName='NoTransferHomeDrive')]
Param(
[Parameter(Mandatory=$True, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True,Position=1)]
[string]$Username,
[Parameter(ParameterSetName='RetainGroups',Position=2)]
[Parameter(ParameterSetName='RetainGroupsWTran',Position=2)]
[switch]$RetainGroups,
[Parameter(ParameterSetName='RemoveFromAllGroups',Position=2)]
[Parameter(ParameterSetName='RemoveFromAllGroupsWTran',Position=2)]
[switch]$RemoveFromAllGroups,
[Parameter(ParameterSetName='TransferHomeDrive', Position=3)]
[Parameter(ParameterSetName='RetainGroupsWTran', Position=3)]
[Parameter(ParameterSetName='RemoveFromAllGroupsWTran', Position=3)]
[switch]$TransferHomeDrive,
[Parameter(ParameterSetName='TransferHomeDrive', Mandatory=$True, Position=4)]
[Parameter(ParameterSetName='RetainGroupsWTran', Mandatory=$True, Position=4)]
[Parameter(ParameterSetName='RemoveFromAllGroupsWTran', Mandatory=$True, Position=4)]
[string]$OldServer,
[Parameter(ParameterSetName='TransferHomeDrive', Mandatory=$True, Position=5)]
[Parameter(ParameterSetName='RetainGroupsWTran', Mandatory=$True, Position=5)]
[Parameter(ParameterSetName='RemoveFromAllGroupsWTran', Mandatory=$True, Position=5)]
[string]$NewServer
)
}
Which will generate the following Get-Help output:
Move-AccountOut [-Username] <string> [<CommonParameters>]
Move-AccountOut [-Username] <string> [[-RetainGroups]] [[-TransferHomeDrive]] [-OldServer] <string> [-NewServer] <string> [<CommonParameters>]
Move-AccountOut [-Username] <string> [[-RetainGroups]] [<CommonParameters>]
Move-AccountOut [-Username] <string> [[-RemoveFromAllGroups]] [[-TransferHomeDrive]] [-OldServer] <string> [-NewServer] <string> [<CommonParameters>]
Move-AccountOut [-Username] <string> [[-RemoveFromAllGroups]] [<CommonParameters>]
Move-AccountOut [-Username] <string> [[-TransferHomeDrive]] [-OldServer] <string> [-NewServer] <string> [<CommonParameters>]
The parameter I am having trouble with is the bottom one (transfer only). I can run the command with username, username+retain, username+remove, username+retain+transfer and username+remove+transfer. But transfer without a retain or remove does not work. When run, it throws the following error:
Move-AccountOut : Parameter set cannot be resolved using the specified named parameters.
At line:33 char:1
+ Move-AccountOut -Username X -TransferHomeDrive -OldServer X -NewServer Y
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Move-AccountOut], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Move-AccountOut
I can't figure out why, given that it appears to be a valid parameter set according to my Get-Help output.
Thank you for the output, here is the key (emphasis mine):
Remaining valid parameter set: RetainGroupsWTran
Remaining valid parameter set: RemoveFromAllGroupsWTran
Remaining valid parameter set: TransferHomeDrive
This happens after all parameters have been bound, and it shows that there are 3 valid parameter sets remaining.
TransferHomeDrive is the parameter set you want.
So why are the other ones there?
RetainGroupsWTran should only be possible if -RetainGroups is specified, and RemoveFromAllGroupsWTran should only be possible if -RemoveFromAllGroups is specified.
However, you can also see in the Get-Help output that there is no parameter set where those switches are mandatory, and this is the problem.
Your updated definition looks like the following:
function Move-AccountOut {
[CmdletBinding(DefaultParameterSetName='NoTransferHomeDrive')]
Param(
[Parameter(Mandatory=$True, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True,Position=1)]
[string]$Username,
[Parameter(ParameterSetName='RetainGroups',Position=2)]
[Parameter(Mandatory=$true,ParameterSetName='RetainGroupsWTran',Position=2)]
[switch]$RetainGroups,
[Parameter(ParameterSetName='RemoveFromAllGroups',Position=2)]
[Parameter(Mandatory=$true,ParameterSetName='RemoveFromAllGroupsWTran',Position=2)]
[switch]$RemoveFromAllGroups,
[Parameter(ParameterSetName='TransferHomeDrive', Position=3)]
[Parameter(ParameterSetName='RetainGroupsWTran', Position=3)]
[Parameter(ParameterSetName='RemoveFromAllGroupsWTran', Position=3)]
[switch]$TransferHomeDrive,
[Parameter(ParameterSetName='TransferHomeDrive', Mandatory=$True, Position=4)]
[Parameter(ParameterSetName='RetainGroupsWTran', Mandatory=$True, Position=4)]
[Parameter(ParameterSetName='RemoveFromAllGroupsWTran', Mandatory=$True, Position=4)]
[string]$OldServer,
[Parameter(ParameterSetName='TransferHomeDrive', Mandatory=$True, Position=5)]
[Parameter(ParameterSetName='RetainGroupsWTran', Mandatory=$True, Position=5)]
[Parameter(ParameterSetName='RemoveFromAllGroupsWTran', Mandatory=$True, Position=5)]
[string]$NewServer
)
}
I've made them mandatory within the parameter sets that were showing up in the trace output.
I think that you should also make them mandatory in the RetainGroups and RemoveFromAllGroups parameter sets as well, but it's not shown above.
Related
I'm trying to use Parameter Sets to replicate this functionality:
if (($hostName) -or ($databaseName) -and (!$databasePassword)) {
throw "If hostName or databaseName specified, you must use databasePassword parameter."
}
Simple example of what I have so far:
[Parameter(Mandatory=$false, ParameterSetName="Test")]
[string]$hostName,
[Parameter(Mandatory=$false, ParameterSetName="Test")]
[string]$databaseName,
[Parameter(Mandatory=$false, ParameterSetName="Test")]
[string]$databasePassword
This is not working. I can supply $hostName without $databasePassword for example, or $dataBasename without $databasePassword and the function runs.
What am I missing?
Make two parameter sets, make $Hostname mandatory in the first, make $DatabaseName optional in the first and mandatory in the other, make $DatabasePassword mandatory in both.
[CmdletBinding(DefaultParameterSetName='host')]
Param(
[Parameter(ParameterSetName='host', Mandatory=$true)]
[string]$Hostname,
[Parameter(ParameterSetName='host', Mandatory=$false)]
[Parameter(ParameterSetName='dbname', Mandatory=$true)]
[string]$DatabaseName,
[Parameter(ParameterSetName='host', Mandatory=$true)]
[Parameter(ParameterSetName='dbname', Mandatory=$true)]
[string]$DatabasePassword
)
Set databasePassword to be mandatory?
[Parameter(Mandatory=$true, ParameterSetName="Test")]
[string]$databasePassword
I'm writing a function for which two parameters should be exclusive and optional.
Here are valid inputs:
new-event -Title sometitle -Text sometext -TimestampHappened 1234567 -SomeOtherOptionalParam somestring
new-event -Title sometitle -Text sometext -DateHappened (get-date) -SomeOtherOptionalParam somestring
new-event -Title sometitle -Text sometext -SomeOtherOptionalParam somestring
new-event -Title sometitle -Text sometext
Here is an invalid input:
new-event -Title sometitle -Text sometext -DateHappened (get-date) -TimestampHappened 1234567 -SomeOtherOptionalParam somestring
Here is my code so far:
[CmdletBinding()]
# Most parameters belong to Default, New-Event:ByDate and New-Event:ByTimestamp parameter sets
param (
[Parameter(
Position=0,
Mandatory=$True,
ParameterSetName="Default"
)]
[Parameter(
Position=0,
Mandatory=$True,
ParameterSetName="New-Event:ByDate"
)]
[Parameter(
Position=0,
Mandatory=$True,
ParameterSetName="New-Event:ByTimestamp"
)]
[ValidateNotNullOrEmpty()]
[String]$Title,
[Parameter(
Position=1,
Mandatory=$True,
ParameterSetName="Default"
)]
[Parameter(
Position=1,
Mandatory=$True,
ParameterSetName="New-Event:ByDate"
)]
[Parameter(
Position=1,
Mandatory=$True,
ParameterSetName="New-Event:ByTimestamp"
)]
[ValidateNotNullOrEmpty()]
[String]$Text,
[Parameter(
Position=2,
Mandatory=$False,
ParameterSetName="New-Event:ByDate"
)]
[ValidateNotNullOrEmpty()]
[datetime]$DateHappened,
[Parameter(
Position=2,
Mandatory=$False,
ParameterSetName="New-Event:ByTimestamp"
)]
[ValidateNotNullOrEmpty()]
[Double]$TimestampHappened,
[Parameter(
Position=3,
Mandatory=$False,
ParameterSetName="Default"
)]
[Parameter(
Position=3,
Mandatory=$False,
ParameterSetName="New-Event:ByDate"
)]
[Parameter(
Position=3,
Mandatory=$False,
ParameterSetName="New-Event:ByTimestamp"
)]
[String]$SomeOtherParam,
...
Here is what I get when I call Get-Help:
PS> get-help New-Event
NAME
New-Event
SYNOPSIS
Post an event to the stream.
SYNTAX
New-Event [-Title] <String> [-Text] <String> [[-TimestampHappened] <Double>] [[-Priority] <String>] [[-Hostname] <String>] [[-Tags] <String[]>] [[-AlertType] <String>] [<CommonParameters>]
New-Event [-Title] <String> [-Text] <String> [[-DateHappened] <DateTime>] [[-Priority] <String>] [[-Hostname] <String>] [[-Tags] <String[]>] [[-AlertType] <String>] <String>] [<CommonParameters>]
New-Event [-Title] <String> [-Text] <String> [[-Priority] <String>] [[-Hostname] <String>] [[-Tags] <String[]>] [[-AlertType] <String>] [<CommonParameters>]
However here is the error I get when I try to call the function with only the two mandatory parameters:
New-Event -Title test -Text text
New-Event : Parameter set cannot be resolved using the specified named parameters.
At line:1 char:1
+ New-Event -Title test -Text text
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [New-Event], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,New-Event
I'm missing something here, but I can't figure out what...
How can I get two parameters that are mutually exclusive and optional?
This makes perfect sense. You have 3 parameter sets, and the 2 mandatory parameters are included on every set. How could PowerShell determine which set you meant to use?
Luckily the [CmdletBinding()] attribute can take a parameter that helps with this exact case: DefaultParameterSetName. Setting this allows PowerShell to use this set in the case of (certain) ambiguities. Use it like so:
[CmdletBinding(DefaultParameterSetName='Default')]
Note that in this case, you named it default; it could have been named anything.
When a script's signature is differentiated (singularly) by an argument, parameter sets make sense to me.
Example:
.\myscript.ps1 -InputFile [-Optional1] [-Optional2]...
.\myscript.ps1 -ArrayOfNames [-Optional1] [-Optional2]...
My question is: Are parameter sets the logical choice when you wish to support parallel (or multiple) dependencies as explained below?
Here is my current scenario.
I'm adding support for an existing script that queries logs containing time stamps. The script should accept a csv file or an array of smtp addresses to identify which users to query.
The script should also support begin and end date parameters or an integer value to facilitate reporting n number of days in the past, calculated from the current date.
The outcome I wish to support is:
.\myScript -InputFile -StartDate -EndDate [-Optional1] [-Optional2]...
.\myScript -InputFile -LastNumDays [-Optional1] [-Optional2]...
.\myScript -Smtp -StartDate -EndDate [-Optional1] [-Optional2]...
.\myScript -Smtp -LastNumDays [-Optional1] [-Optional2]...
Either of the following two parameter definitions work well if I don't attempt to combine my two requirements:
[Parameter(Mandatory=$true, ParameterSetName="Input")]
[ValidateScript({Test-Path -Path $_ -PathType Leaf})][string] $InputFile,
[Parameter(Mandatory=$true, ParameterSetName="NoInput")]
[ValidateNotNullOrEmpty()][String[]] $Smtp
Get-Help displays expected usage as:
.\myScript.ps1 -InputFile <String> [<CommonParameters>]
.\myScript.ps1 -Smtp <String[]> [<CommonParameters>]
If I configure the following instead:
[Parameter(Mandatory=$true, ParameterSetName="NotRange")]
[ValidateNotNullOrEmpty()][int] $LastNumDays = 30, # init 30 days default
[Parameter(Mandatory=$true, ParameterSetName="Range")]
[ValidateNotNullOrEmpty()][Alias("Start")] [DateTime] $StartDate,
[Parameter(Mandatory=$true, ParameterSetName="Range")]
[ValidateNotNullOrEmpty()][Alias("End")] [DateTime] $EndDate
Get-Help displays expected usage as:
.\myScript.ps1 -LastNumDays <Int32> [<CommonParameters>]
.\myScript.ps1 -StartDate <DateTime> -EndDate <DateTime> [<CommonParameters>]
The problem is that I can't seem to incorporate both my dependencies as described at the beginning of this post. An example of just one of my unsuccessful attempts to combine these two logical dependencies using parameter sets is as follows:
[Parameter(Mandatory=$true, ParameterSetName="Input")]
[ValidateScript({Test-Path -Path $_ -PathType Leaf})][string] $InputFile,
[Parameter(Mandatory=$true, ParameterSetName="NoInput")]
[ValidateNotNullOrEmpty()][String[]] $Smtp,
[Parameter(Mandatory=$true, ParameterSetName="NotRange")]
[Parameter(Mandatory=$true, ParameterSetName="Input")]
[Parameter(Mandatory=$true, ParameterSetName="NoInput")]
[ValidateNotNullOrEmpty()][int] $LastNumDays = 30, # init 30 days default
[Parameter(Mandatory=$true, ParameterSetName="Range")]
[Parameter(Mandatory=$true, ParameterSetName="Input")]
[Parameter(Mandatory=$true, ParameterSetName="NoInput")]
[ValidateNotNullOrEmpty()][Alias("Start")] [DateTime] $StartDate,
[Parameter(Mandatory=$true, ParameterSetName="Range")]
[Parameter(Mandatory=$true, ParameterSetName="Input")]
[Parameter(Mandatory=$true, ParameterSetName="NoInput")]
[ValidateNotNullOrEmpty()][Alias("End")] [DateTime] $EndDate
Get-Help results are incorrect b/c the first two usage statements allow LastNumDays and Start/EndDate parameters to be used at the same time:
.\myScript.ps1 -InputFile <String> -LastNumDays <Int32> -StartDate <DateTime> -EndDate <DateTime> [<CommonParameters>]
.\myScript.ps1 -Smtp <String[]> -LastNumDays <Int32> -StartDate <DateTime> -EndDate <DateTime> [<CommonParameters>]
.\myScript.ps1 -LastNumDays <Int32> [<CommonParameters>]
.\myScript.ps1 -StartDate <DateTime> -EndDate <DateTime> [<CommonParameters>]
I've tested different combinations of mandatory true/false and including/omitting my named parameter sets with no success.
I'm suspecting now that my requirements may not be fitting for the use case parameter sets were intended to support but am left to wonder what pattern and practice I should be using instead.
How can I properly define usage syntax for these two dependencies if not using parameter sets? I feel that I must avoid resorting to tests in my code that announce dependencies that are not defined in Get-Help.
Thank you!
You need to make each parameter set unique, so PowerShell can distinguish one from another. For simplicity reasons I'll name the parameter sets A through D:
A: -InputFile -StartDate -EndDate
B: -InputFile -LastNumDays
C: -Smtp -StartDate -EndDate
D: -Smtp -LastNumDays
Now associate each parameter with each parameter set it appears in:
Param(
[Parameter(Mandatory=$true, ParameterSetName="A")]
[Parameter(Mandatory=$true, ParameterSetName="B")]
[string]$InputFile,
[Parameter(Mandatory=$true, ParameterSetName="C")]
[Parameter(Mandatory=$true, ParameterSetName="D")]
[String[]]$Smtp,
[Parameter(Mandatory=$true, ParameterSetName="B")]
[Parameter(Mandatory=$true, ParameterSetName="D")]
[int]$LastNumDays,
[Parameter(Mandatory=$true, ParameterSetName="A")]
[Parameter(Mandatory=$true, ParameterSetName="C")]
[DateTime]$StartDate,
[Parameter(Mandatory=$true, ParameterSetName="A")]
[Parameter(Mandatory=$true, ParameterSetName="C")]
[DateTime]$EndDate
)
Output:
PS C:\> .\test.ps1 -?
test.ps1 -InputFile <string> -LastNumDays <int> [<CommonParameters>]
test.ps1 -InputFile <string> -StartDate <datetime> -EndDate <datetime> [<CommonParameters>]
test.ps1 -Smtp <string[]> -LastNumDays <int> [<CommonParameters>]
test.ps1 -Smtp <string[]> -StartDate <datetime> -EndDate <datetime> [<CommonParameters>]
Note that it's pointless to provide a default value for a mandatory parameter (-LastNumDays), because you're required to provide a value anyway.
I was struggling in a situation where I need to make some parameters mandatory ONLY if a switch or combination of switches is used. Below is the example of what I am trying to do:
[CmdletBinding(DefaultParameterSetName='DefaultConfiguration')]
Param
(
[Parameter(Mandatory=$true)][String]$Location,
[Parameter(Mandatory=$true)][String]$DPMServername,
[Parameter(Mandatory=$False, ParameterSetName='CustomConfiguration')]
[Switch]$CustomizeDPMSubscriptionSettings,
[Parameter(Mandatory=$True, ParameterSetName='CustomConfiguration')]
[String]$StagingAreaPath,
[Parameter(Mandatory=$False, ParameterSetName='EncryptionSettings')]
[Parameter(ParameterSetName='CustomConfiguration')]
[Switch]$SetEncryption,
[Parameter(Mandatory=$true, ParameterSetName='EncryptionSettings')]
[Parameter(Mandatory=$False, ParameterSetName='CustomConfiguration')]
[String]$EncryptionPassPhrase,
[Parameter(Mandatory=$False, ParameterSetName='ProxyEnabled')]
[Parameter(ParameterSetName='CustomConfiguration')]
[Switch]$SetProxy,
[Parameter(Mandatory=$true, ParameterSetName='ProxyEnabled')]
[Parameter(ParameterSetName='CustomConfiguration')]
[String]$ProxyServerAddress,
[Parameter(Mandatory=$true, ParameterSetName='ProxyEnabled')]
[Parameter(Mandatory=$False, ParameterSetName='CustomConfiguration')]
[String]$ProxyServerPort
)
Here, I need to follow below conditions:
If -CustomizeDPMSubscriptionSettings (Switch) parameter is used,
it must ask for the Staging AreaPath ---- This is Working fine
ONLY when -CustomizeDPMSubscriptionSettings (Switch) parameter is
used with -SetEncryption, it must ask for -EncryptionPassPhrase
And ONLY when -CustomizeDPMSubscriptionSettings (Switch) parameter is
used with -SetProxy, it must ask for -ProxyServerAddress and -ProxyServerPort
Sorry if this sounds like a repeated question but other posts I found here are not helping me solve my issue. I am confused :-(
NOTE: Above code is part of what I was trying with different combinations. Please correct as necessary.
Here is a solution that seems to do what you expect.
What I did was create a parameter set for each possible combination.
- CustomConfiguration
- EncryptionSettings
- ProxyEnabled
- EncryptionAndProxy
One limitation is that it will not prompt for specific missing parameters unless using EncryptionAndProxy, but will instead state that it cannot resolve the parameter set.
[CmdletBinding(DefaultParameterSetName='DefaultConfiguration')]
Param
(
[Parameter(Mandatory=$true)][String]$Location,
[Parameter(Mandatory=$true)][String]$DPMServername,
[Parameter(Mandatory=$True, ParameterSetName='CustomConfiguration')]
[Parameter(Mandatory=$True, ParameterSetName='EncryptionSettings')]
[Parameter(Mandatory=$True, ParameterSetName='ProxyEnabled')]
[Parameter(Mandatory=$True, ParameterSetName='EncryptionAndProxy')]
[Switch]$CustomizeDPMSubscriptionSettings,
[Parameter(Mandatory=$True, ParameterSetName='CustomConfiguration')]
[Parameter(Mandatory=$True, ParameterSetName='EncryptionSettings')]
[Parameter(Mandatory=$True, ParameterSetName='ProxyEnabled')]
[Parameter(Mandatory=$True, ParameterSetName='EncryptionAndProxy')]
[String]$StagingAreaPath,
[Parameter(Mandatory=$True, ParameterSetName='EncryptionSettings')]
[Parameter(Mandatory=$True, ParameterSetName='EncryptionAndProxy')]
[Switch]$SetEncryption,
[Parameter(Mandatory=$true, ParameterSetName='EncryptionSettings')]
[Parameter(Mandatory=$True, ParameterSetName='EncryptionAndProxy')]
[String]$EncryptionPassPhrase,
[Parameter(Mandatory=$True, ParameterSetName='ProxyEnabled')]
[Parameter(Mandatory=$True, ParameterSetName='EncryptionAndProxy')]
[Switch]$SetProxy,
[Parameter(Mandatory=$true, ParameterSetName='ProxyEnabled')]
[Parameter(Mandatory=$True, ParameterSetName='EncryptionAndProxy')]
[String]$ProxyServerAddress,
[Parameter(Mandatory=$true, ParameterSetName='ProxyEnabled')]
[Parameter(Mandatory=$True, ParameterSetName='EncryptionAndProxy')]
[String]$ProxyServerPort
)
I'm looking into a second potential solution based on dynamic parameters.
Edit: As promised, here's a solution based on dynamic parameters
[CmdletBinding(DefaultParameterSetName='DefaultConfiguration')]
Param
(
[Parameter(Mandatory=$true)][String]$Location,
[Parameter(Mandatory=$true)][String]$DPMServername,
[Switch]$CustomizeDPMSubscriptionSettings,
[Switch]$SetEncryption,
[Switch]$SetProxy
)
DynamicParam
{
$paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary
$attributes = New-Object System.Management.Automation.ParameterAttribute
$attributes.ParameterSetName = "__AllParameterSets"
$attributes.Mandatory = $true
$attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute]
$attributeCollection.Add($attributes)
# If "-SetEncryption" is used, then add the "EncryptionPassPhrase" parameter
if($SetEncryption)
{
$dynParam1 = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("EncryptionPassPhrase", [String], $attributeCollection)
$paramDictionary.Add("EncryptionPassPhrase", $dynParam1)
}
# If "-SetProxy" is used, then add the "ProxyServerAddress" "ProxyServerPort" and parameters
if($SetProxy)
{
$dynParam1 = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("ProxyServerAddress", [String], $attributeCollection)
$paramDictionary.Add("ProxyServerAddress", $dynParam1)
$dynParam2 = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("ProxyServerPort", [String], $attributeCollection)
$paramDictionary.Add("ProxyServerPort", $dynParam2)
}
# If "-CustomizeDPMSubscriptionSettings" is used, then add the "StagingAreaPath" parameter
if($CustomizeDPMSubscriptionSettings)
{
$dynParam1 = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("StagingAreaPath", [String], $attributeCollection)
$paramDictionary.Add("StagingAreaPath", $dynParam1)
}
return $paramDictionary
}
Process{
foreach($key in $PSBoundParameters.keys)
{
Set-Variable -Name $key -Value $PSBoundParameters."$key" -Scope 0
}
}
What this one does is dynamically add parameters to your function based on the presence of each switch.
This supports autocompletion, and has better support for missing parameters. It will explicitly ask for missing parameters if the corresponding switch is used.
Second edit: I added the Process section that's mandatory with this construct, as well as the variable creation bit, which makes things much easier.
I am building a function which will have three distinct parameter sets, and two of those sets will overlap with the third. The options would look like this:
A B
A C
A (D E F)
A B (D E F)
A C (D E F)
To make it a little more clear, here is a partially completed version the function:
function Move-AccountOut {
[CmdletBinding(DefaultParameterSetName='NoTransferHomeDrive')]
Param(
[Parameter(Mandatory=$True, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True)]
[string]$Username,
[Parameter(ParameterSetName='RetainGroups')]
[switch]$RetainGroups,
[Parameter(ParameterSetName='RemoveFromAllGroups')]
[switch]$RemoveFromAllGroups,
[Parameter(ParameterSetName='TransferHomeDrive', Mandatory=$False)]
[switch]$TransferHomeDrive,
[Parameter(ParameterSetName='TransferHomeDrive', Mandatory=$True)]
[string]$OldServer,
[Parameter(ParameterSetName='TransferHomeDrive', Mandatory=$True)]
[string]$NewServer
)
}
The purpose of the function is to automate the process of transferring out an AD account to another location within the company. RetainGroups would automatically retain the users groups when set, and RemoveFromAllGroups would automatically remove the user from their groups. The two switches should not be able to be used together. Additionally, if TransferHomeDrive is set, it will call a function to schedule a transfer using an internal tool.
To put it another way, RetainGroups and RemoveFromAllGroups should be a member of all parameter sets (similar to Username), but should not be able to be used together.
I have tried two ways. The first:
function Move-AccountOut {
[CmdletBinding(DefaultParameterSetName='NoTransferHomeDrive')]
Param(
[Parameter(Mandatory=$True, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True)]
[string]$Username,
[Parameter(ParameterSetName='RetainGroups')]
[switch]$RetainGroups,
[Parameter(ParameterSetName='RemoveFromAllGroups')]
[switch]$RemoveFromAllGroups,
[Parameter(ParameterSetName='TransferHomeDrive', Mandatory=$False)]
[Parameter(ParameterSetName='RetainGroups')]
[Parameter(ParameterSetName='RemoveFromAllGroups')]
[switch]$TransferHomeDrive,
[Parameter(ParameterSetName='TransferHomeDrive', Mandatory=$True)]
[Parameter(ParameterSetName='RetainGroups')]
[Parameter(ParameterSetName='RemoveFromAllGroups')]
[string]$OldServer,
[Parameter(ParameterSetName='TransferHomeDrive', Mandatory=$True)]
[Parameter(ParameterSetName='RetainGroups')]
[Parameter(ParameterSetName='RemoveFromAllGroups')]
[string]$NewServer
)
}
Using this technique, retain and remove cannot be used together, but OldServer and NewServer are no longer mandatory. If I change them to:
[Parameter(ParameterSetName='TransferHomeDrive', Mandatory=$True)]
[Parameter(ParameterSetName='RetainGroups', Mandatory=$True)]
[string]$OldServer,
[Parameter(ParameterSetName='TransferHomeDrive', Mandatory=$True)]
[Parameter(ParameterSetName='RetainGroups', Mandatory=$True)]
[string]$NewServer
They will be mandatory, but it no longer cares whether TransferHomeDrive is set.
If I set it up the opposite way:
function Move-AccountOut {
[CmdletBinding(DefaultParameterSetName='NoTransferHomeDrive')]
Param(
[Parameter(Mandatory=$True, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True)]
[string]$Username,
[Parameter(ParameterSetName='RetainGroups')]
[Parameter(ParameterSetName='TransferHomeDrive')]
[switch]$RetainGroups,
[Parameter(ParameterSetName='RemoveFromAllGroups')]
[Parameter(ParameterSetName='TransferHomeDrive')]
[switch]$RemoveFromAllGroups,
[Parameter(ParameterSetName='TransferHomeDrive', Mandatory=$False)]
[switch]$TransferHomeDrive,
[Parameter(ParameterSetName='TransferHomeDrive', Mandatory=$True)]
[string]$OldServer,
[Parameter(ParameterSetName='TransferHomeDrive', Mandatory=$True)]
[string]$NewServer
)
}
Then OldServer and NewServer will be mandatory, but RetainGroups and RemoveFromAllGroups can be used together. Additionally, if I use retain and remove together, then OldServer and NewServer become mandatory, but not when they are used on their own.
How do I make this work?
Ok, I think I understand this. The possible combinations you want are:
-RetainGroups
-RemoveFromAllGroups
-RetainGroups plus -TransferHomeDrive
-RemoveFromAllGroups plus -TransferHomeDrive
Only -UserName
-UserName plus -TransferHomeDrive
I am assuming that -OldServer and -NewServer only apply when moving the home drive, so whenever you are moving the home drive, they are mandatory. If that is not the case, let me know.
So what you have here are 6 parameter sets. As powerful as powershell's parameter set magic is, there isn't a good way to say "these 2 switches are mutually exclusive but should also be available in all parameter sets" so you have to multiplex it and repeat every parameter set with one or the other.
function Move-AccountOut {
[CmdletBinding(DefaultParameterSetName='OnlyUser')]
Param(
[Parameter(
Mandatory=$True,
ValueFromPipeline=$True,
ValueFromPipelineByPropertyName=$True
)]
[string]
$Username,
[Parameter(
Mandatory=$True,
ParameterSetName='RetainOnly'
)]
[Parameter(
Mandatory=$True,
ParameterSetName='RetainAndTransfer'
)]
[switch]
$RetainGroups,
[Parameter(
Mandatory=$True,
ParameterSetName='RemoveOnly'
)]
[Parameter(
Mandatory=$True,
ParameterSetName='RemoveAndTransfer'
)]
[switch]
$RemoveFromAllGroups,
[Parameter(
Mandatory=$True,
ParameterSetName='RetainAndTransfer'
)]
[Parameter(
Mandatory=$True,
ParameterSetName='RemoveAndTransfer'
)]
[Parameter(
Mandatory=$True,
ParameterSetName='TransferOnly'
)]
[switch]
$TransferHomeDrive,
[Parameter(
Mandatory=$True,
ParameterSetName='RetainAndTransfer'
)]
[Parameter(
Mandatory=$True,
ParameterSetName='RemoveAndTransfer'
)]
[Parameter(
Mandatory=$True,
ParameterSetName='TransferOnly'
)]
[string]
$OldServer,
[Parameter(
Mandatory=$True,
ParameterSetName='RetainAndTransfer'
)]
[Parameter(
Mandatory=$True,
ParameterSetName='RemoveAndTransfer'
)]
[Parameter(
Mandatory=$True,
ParameterSetName='TransferOnly'
)]
[string]
$NewServer
)
}
The output of Get-Help Move-AccountOut:
Move-AccountOut -Username <string> [<CommonParameters>]
Move-AccountOut -Username <string> -RetainGroups -TransferHomeDrive -OldServer <string> -NewServer <string> [<CommonParameters>]
Move-AccountOut -Username <string> -RetainGroups [<CommonParameters>]
Move-AccountOut -Username <string> -RemoveFromAllGroups -TransferHomeDrive -OldServer <string> -NewServer <string> [<CommonParameters>]
Move-AccountOut -Username <string> -RemoveFromAllGroups [<CommonParameters>]
Move-AccountOut -Username <string> -TransferHomeDrive -OldServer <string> -NewServer <string> [<CommonParameters>]
Simplifying It
If you want to make it less daunting, you might consider consolidating the remove and retain switches into a single parameter, something like this:
[Parameter(
Mandatory=$false # you can leave this out
)]
[ValidateSet(
'None',
'Retain',
'RemoveAll'
)]
[String]
$GroupAction = 'None'
This would reduce your parameter sets down to 2, and make your entire definition look like this:
function Move-AccountOut {
[CmdletBinding(DefaultParameterSetName='OnlyUser')]
Param(
[Parameter(
Mandatory=$True,
ValueFromPipeline=$True,
ValueFromPipelineByPropertyName=$True
)]
[string]
$Username,
[ValidateSet(
'None',
'Retain',
'RemoveAll'
)]
[String]
$GroupAction = 'None' ,
[Parameter(
Mandatory=$True,
ParameterSetName='TransferOnly'
)]
[switch]
$TransferHomeDrive,
[Parameter(
Mandatory=$True,
ParameterSetName='TransferOnly'
)]
[string]
$OldServer,
[Parameter(
Mandatory=$True,
ParameterSetName='TransferOnly'
)]
[string]
$NewServer
)
}
With the following Get-Help output:
Move-AccountOut -Username <string> [-GroupAction <string> {None | Retain | RemoveAll}] [<CommonParameters>]
Move-AccountOut -Username <string> -TransferHomeDrive -OldServer <string> -NewServer <string> [-GroupAction <string> {None | Retain | RemoveAll}] [<CommonParameters>]
I do want to point out that although that's simpler to define that doesn't mean it's better. It may be that you want to optimize your parameter sets for the caller which can be especially important if this is a function you plan on using interactively a lot from the shell, rather than calling from other scripts (and it seems like this may be the case).
So adding some complexity in the definition to make it easier to use might be the right thing to do.
By adding two more Parameter Sets you can do what you want. This is needed because you have 3 sets now, plus a non-set parameter (which technically puts it in the __AllParameterSets set if I remember right). So that's 4 ways of doing it. You need 6 ways of doing it if I am reading your question correctly. You want all of the following options:
Move-AccountOut -Username <string> [<CommonParameters>]
Move-AccountOut -Username <string> [-RetainGroups] [-TransferHomeDrive] [-OldServer <string>] [-NewServer <string>] [<CommonParameters>]
Move-AccountOut -Username <string> [-RetainGroups] [<CommonParameters>]
Move-AccountOut -Username <string> [-RemoveFromAllGroups] [-TransferHomeDrive] [-OldServer <string>] [-NewServer <string>] [<CommonParameters>]
Move-AccountOut -Username <string> [-RemoveFromAllGroups] [<CommonParameters>]
Move-AccountOut -Username <string> -OldServer <string> -NewServer <string> [-TransferHomeDrive] [<CommonParameters>]
So we will add the RemoveFromAllGroupsWTran and RetainGroupsWTran Parameter Sets, add them both to $TransferHomeDrive, $OldServer, and $NewServer (removing the other related set names from them), then add each to its respective switch parameter. It ends up looking like this:
function Move-AccountOut {
[CmdletBinding(DefaultParameterSetName='NoTransferHomeDrive')]
Param(
[Parameter(Mandatory=$True, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True)]
[string]$Username,
[Parameter(ParameterSetName='RetainGroups')]
[Parameter(ParameterSetName='RetainGroupsWTran')]
[switch]$RetainGroups,
[Parameter(ParameterSetName='RemoveFromAllGroups')]
[Parameter(ParameterSetName='RemoveFromAllGroupsWTran')]
[switch]$RemoveFromAllGroups,
[Parameter(ParameterSetName='TransferHomeDrive', Mandatory=$False)]
[Parameter(ParameterSetName='RetainGroupsWTran')]
[Parameter(ParameterSetName='RemoveFromAllGroupsWTran')]
[switch]$TransferHomeDrive,
[Parameter(ParameterSetName='TransferHomeDrive', Mandatory=$True)]
[Parameter(ParameterSetName='RetainGroupsWTran')]
[Parameter(ParameterSetName='RemoveFromAllGroupsWTran')]
[string]$OldServer,
[Parameter(ParameterSetName='TransferHomeDrive', Mandatory=$True)]
[Parameter(ParameterSetName='RetainGroupsWTran')]
[Parameter(ParameterSetName='RemoveFromAllGroupsWTran')]
[string]$NewServer
)
}
You can also use [ValidateScript()], if have two Mandatory = false parameters in all parameter sets, and you need to use them only together, e.g.:
function SomeFunction {
[CmdletBinding()]
Param(
[Parameter (Mandatory = $true,
ParameterSetName = "A")]
[Parameter (Mandatory = $true,
ParameterSetName = "B")]
[Parameter (Mandatory = $true,
ParameterSetName = "C")]
[switch]$Param1,
[Parameter (Mandatory = $true,
ParameterSetName = "A")]
[switch]$Param2,
[Parameter (Mandatory = $true,
ParameterSetName = "B")]
[string]$Param3,
[Parameter (Mandatory = $true,
ParameterSetName = "C")]
[string]$Param4,
[Parameter (Mandatory = $false,]
[ValidateScript({
if ($Param6) {
$True
}
else {
throw "This parameter will work only with parameter [Param6]"
}
}
)]
[string]$Param5,
[Parameter (Mandatory = $false)]
[ValidateScript({
if ($Param5) {
$True
}
else {
throw "This parameter will work only with parameter [Param5]"
}
}
)]
[string]$Param6
...
}