[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

Powershell require at least one of two parameters to be mandatory

Posted on 2014-12-29
14
Medium Priority
?
1,159 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 71

Accepted Solution

by:
Qlemo earned 1000 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
Learn Veeam advantages over legacy backup

Every day, more and more legacy backup customers switch to Veeam. Technologies designed for the client-server era cannot restore any IT service running in the hybrid cloud within seconds. Learn top Veeam advantages over legacy backup and get Veeam for the price of your renewal

 
LVL 41

Assisted Solution

by:footech
footech earned 1000 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 71

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 71

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 71

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 71

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

Does Powershell have you tied up in knots?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

Question has a verified solution.

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

In threads here at EE, each comment has a unique Identifier (ID). It is easy to get the full path for an ID via the right-click context menu. However, we often want to post a short link within a thread rather than the full link. This article shows a…
A walk-through example of how to obtain and apply new DID phone numbers to your cloud PBX enabled users that are configured in Office 365. Whether you have 1, 10 or 100+ users in your tenant, it's quite easy to get them phone-enabled and making/rece…
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…
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…
Suggested Courses

649 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