Solved

Powershell require at least one of two parameters to be mandatory

Posted on 2014-12-29
14
921 Views
Last Modified: 2015-01-04
Okay this should be super simple but for some reason Googling and searching this site has not provided me with an answer to this question (or more likely I am not providing the correct search terms), so here goes.

Within a Powershell script I want to make sure the user passes a value for at LEAST one parameter out of a possible two when calling a particular Powershell script.

So this should produce an error:

.\scriptname

However these should not:

.\scriptname -add john
.\scriptname -delete fred
.\scriptname -add john -delete fred

I've read fifty different things you can do with parameters (switches, dynamic parameters, parameter sets) but can't seem to figure out how to just make at least one OF two parameters mandatory.  I know how to make single parameter mandatory or to make two parameters mandatory but NOT how to make it so the user has to pass either ONE or TWO parameters but NOT zero).

Any help is much appreciated. Thanks!
0
Comment
Question by:rsts_support
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
  • 3
  • +2
14 Comments
 
LVL 70

Accepted Solution

by:
Qlemo earned 250 total points
ID: 40522437
You need two parameter sets, each with one mandatory parameter. I would add both parameters to only one of them.
0
 
LVL 10

Expert Comment

by:Michael Ian Claridge
ID: 40522445
As an example, this is an extract from one of my scripts:

# Creates A Mandatory Parameters
[CmdletBinding()]
param(
[parameter(mandatory=$true,Position=1)]
[string]$FileExtension,
 
[parameter(mandatory=$false)]
[string]$FileAge,
 
[parameter(mandatory=$true)]
[string]$FilePath
)

Open in new window

0
 
LVL 29

Expert Comment

by:becraig
ID: 40522451
Simply declare the parameter to be mandatory

param ([Parameter(Mandatory = $true)]  [string[]]$action1,
	[Parameter(Mandatory = $false)]  [string]$action2)

Open in new window



Above will prompt you for a parameter inline when run, if you want to throw and error then do:
param ([Parameter(Mandatory = $true)]  [string[]]$action1$(throw "Action is mandatory, please provide a value.",
	[Parameter(Mandatory = $false)]  [string]$action2)

Open in new window

0
Free eBook: Backup on AWS

Everything you need to know about backup and disaster recovery with AWS, for FREE!

 
LVL 40

Assisted Solution

by:footech
footech earned 250 total points
ID: 40522473
Qlemo's advice is good.  I don't see the others as working.  Here's an example script I threw together.
Param(
    [Parameter(Mandatory = $True, ParameterSetName = "Add")]
    [string]$Add,
    [Parameter(Mandatory = $True, ParameterSetName = "Delete")]
    [Parameter(ParameterSetName = "Add")]
    [string]$Delete
)
Write-Output "Delete: $Delete"
Write-Output "Add: $Add"

Open in new window

0
 
LVL 29

Expert Comment

by:becraig
ID: 40522493
Sorry I seem to have left out "="

param ([Parameter] [string]$action1=$(throw "Action is mandatory, please provide a value."),
	[Parameter]  [string]$action2 )

Open in new window


This will simply provide you the throw you need without circumnavigating the globe.

You can also tweak and play with position of the parameters.

As I indicated in the first post once you set it as Mandatory, the user can simply proceed to add the value in the pipeline.
0
 
LVL 70

Expert Comment

by:Qlemo
ID: 40522626
becraig., that's not true. This only makes the first parameter mandatory, the second optional.
0
 
LVL 29

Expert Comment

by:becraig
ID: 40522669
I think I have misread the OP's expectation.

In re-reading it seems he wants to make BOTH params mandatory but either one can be optional once a param is provided ?

In that event I would probably just evaluate for the existence of the value of the parameter before proceeding, from what you are indicating he wants to throw an error if  "-add" is missing and ALSO throw an error if "-delete" is missing but not to error if either -add or -delete is present ?

My approach for this in the past has been to simply use an if statement to evaluate if the param has been populated with a value at runtime.
0
 
LVL 70

Expert Comment

by:Qlemo
ID: 40522712
The recommendation since PS2 is to use the CmdletBInding feature (with parameter attributes). It is more complex, but allows for much better control, e.g. in regard of pipeline data and parameter aliases.  The parameter set declaration allows for automated help output. Also "mandatory" is not hidden somewhere in the code, but visible in the parameter description.
0
 

Author Comment

by:rsts_support
ID: 40524609
I tried giving both Qlemo AND footech each credit for the answer but as soon as I gave it to Qlemo it wouldn't allow me to award it to footech also. Thought I pressed "partial" answer for Qlemo but maybe I didn't. Can this be fixed by admin? Thanks.

Also as a comment I would like to say that I don't see where in the documentation for parameter sets in Powershell it says that if you create multiple parameter sets and make them all mandatory that the user only actually has to pass ONE parameter...Did I miss that somewhere in the documentation?
0
 
LVL 70

Expert Comment

by:Qlemo
ID: 40524707
Correct. The documentation doesn't tell you directly and obviously that you can make different parameter combinations mandatory, but that is one of the main purposes.
0
 

Author Closing Comment

by:rsts_support
ID: 40527846
I assumed that you would click on the "Accept MultipleAnswers" TWICE (one for each answer).  Didn't realize you would be presented with a second screen where you then would have to check the "Expert Comment" for both people you wanted to credit with answering your question.

I guess my problem is that the word "mandatory" in two parameters sounds like BOTH are...you know MANDATORY. In other words, you have to pass arguments for BOTH, not just be permitted to pass EITHER both OR just one (I wouldn't think the latter we be possible).
0
 
LVL 70

Expert Comment

by:Qlemo
ID: 40527899
Since parameter sets are mutually exclusive, you need to consider each as unique parameter definition.

PowerShell will try to find the best fitting parameter set.
 If it finds only an "-Add" parameter when calling, it will accept it as parameter set "Add".
if you provide "-Delete" only, the first parameter set does not work. There is a second one ("Delete"), and that fits.
If you provide both parameters, only the first parameter set contains both parameters. Note that "-Delete" is not mandatory with "Add" parameter set - you need to read it exactly that way: "mandatory for "Delete" parameter set, but not mandatory for "Add".
0
 

Author Comment

by:rsts_support
ID: 40530905
Thanks Qlemo, that makes sense. Unfortunately I need to ask another related question. I will do it as a separate question though.
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Windows 10 came with  a lot of built in applications, Some organisations leave them there, some will control them using GPO's. This Article is useful for those who do not want to have any applications in their image (example:me).
In this post we will be converting StringData saved within a text file into a hash table. This can be further used in a PowerShell script for replacing settings that are dynamic in nature from environment to environment.
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…

691 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question