Solved

Powershell require at least one of two parameters to be mandatory

Posted on 2014-12-29
14
480 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
  • 5
  • 3
  • 3
  • +2
14 Comments
 
LVL 68

Accepted Solution

by:
Qlemo earned 250 total points
Comment Utility
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
Comment Utility
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 28

Expert Comment

by:becraig
Comment Utility
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
 
LVL 39

Assisted Solution

by:footech
footech earned 250 total points
Comment Utility
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 28

Expert Comment

by:becraig
Comment Utility
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 68

Expert Comment

by:Qlemo
Comment Utility
becraig., that's not true. This only makes the first parameter mandatory, the second optional.
0
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 28

Expert Comment

by:becraig
Comment Utility
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 68

Expert Comment

by:Qlemo
Comment Utility
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
Comment Utility
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 68

Expert Comment

by:Qlemo
Comment Utility
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
Comment Utility
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 68

Expert Comment

by:Qlemo
Comment Utility
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
Comment Utility
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Are you one of those front-line IT Service Desk staff fielding calls, replying to emails, all-the-while working to resolve end-user technological nightmares? I am! That's why I have put together this brief overview of tools and techniques I use in o…
This is a PowerShell web interface I use to manage some task as a network administrator. Clicking an action button on the left frame will display a form in the middle frame to input some data in textboxes, process this data in PowerShell and display…
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
The viewer will learn how to dynamically set the form action using jQuery.

743 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now