powershellparameter-sets

Parameters issue in script


Can someone tell what I am doing wrong in the below I wrote:

function set-harden {
[CmdletBinding(DefaultParameterSetName='NormalHardening')]
param (
[Parameter(ParameterSetName='DoNotRemoveFromDomain')]
[Parameter(ParameterSetName='PermitHTTP' ,Mandatory=$True)]
[Parameter(ParameterSetName='PermitHTTPS' ,Mandatory=$True)]
            [switch]$DONOTRemovefromdomain,

[Parameter(ParameterSetName='PermitHTTP')]
[Parameter(ParameterSetName='DoNotRemoveFromDomain')]
            [switch]$Permithttp,

[Parameter(ParameterSetName='PermitHTTPS')]
[Parameter(ParameterSetName='DoNotRemoveFromDomain')]
        [switch]$Permithttps,

[Parameter(ParameterSetName='NormalHardening')]
            $NormalHardening
 )}

 If($NormalHardening -eq ""){
    Write-Host "Excellent!"
 }

All I want to do is to let the user select -DONOTRemovefromdomain or -Permithttp or even -Permithttps. There could be a variety of options the user has to choose from.

When I run this below I get an error:

PS C:\Temp> set-harden -DONOTRemovefromdomain -Permithttp
set-harden : Parameter set cannot be resolved using the specified named parameters.
At line:1 char:1
+ set-harden -DONOTRemovefromdomain -Permithttp
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [set-harden], ParameterBindingException
    + FullyQualifiedErrorId : AmbiguousParameterSet,set-harden

Also, if I do not specify anything (so it should just go to the parameter NormalHardening) I get an nothing back:

PS C:\Temp> set-harden

PS C:\Temp> 

Solution

  • You've specified two flags, DONOTRemovefromDomain and Permithttp that belong to two parameter sets, DoNotRemoveFromDomain and PermitHttp. The command parser has no way of knowing which parameter set you mean, so you get an error.

    The reason you don't get an error when you don't specify anything is because you've set the default parameter set explicitly to NormalHardening. You've not set the Mandatory flag on the single parameter in this parameter set, and by default parameters are not mandatory so you're not seeing an error.

    Instead of having all these parameter sets why not just have 2, one for the default and one for all the flags you want to set:

    function set-harden {
    [CmdletBinding(DefaultParameterSetName='NormalHardening')]
    param (
    [Parameter(ParameterSetName='Options')]
    [switch]$DONOTRemovefromdomain,
    
    [Parameter(ParameterSetName='Options')]
    [switch]$Permithttp,
    
    [Parameter(ParameterSetName='Options')]
    [switch]$Permithttps,
    
    [Parameter(ParameterSetName='NormalHardening')]
    $NormalHardening
     )}
    
     If($PSCmdlet.ParameterSetName -eq "Options"){
        Write-Host "Excellent!"
     }
    

    How, if the parameter set name is set to Options you can check and apply the flags. If it's set to NormalHarding then you know to use the $NormalHardening parameter.