Reputation: 2172
I have a script where I want to call multiple parameters, which may take multiple arguments, at the same time with the format:
.\MyScript.ps1 -q <int> --args <hostval1> <hostval2> ... <hostvaln>
Right now, I have other parameters besides "q", but they do not need the "--args" parameter. I currently can't figure out how to implement "--args", because I currently have my parameters defined like so:
param(
[Alias('c')]
[string]$csv,
[Alias('h')]
[switch]$help,
[Alias('f')]
[switch]$fields,
[Alias('s')]
[string]$sql,
[Alias('q')]
[int]$query
)
I know I could run it like this to get hostvalues, but it would require a dash:
.\MyScript.ps1 -q 1 -hostval1 -hostval3 -hostval4
This makes
$args[0] = -hostval1
$args[1] = -hostval3
$args[2] = -hostval4
Is there any way to make a "secondary" parameter (e.g. --args) that can only be called with "-q", and accepts multiple values separated by spaces? I could create another parameter, but this would allow it to accidentally be called without the "-q" parameter, and also requires commas between arguments:
[string[]]$hostvals
Is what I'm looking to do possible in powershell? Does anyone have any ideas of what I could do?
Upvotes: 2
Views: 1583
Reputation: 60908
You can try with parametersetname:
[CmdletBinding(DefaultParameterSetName="Q")]
param(
[Alias('c')]
[string]$csv,
[Alias('h')]
[switch]$help,
[Alias('f')]
[switch]$fields,
[Alias('s')]
[string]$sql,
[Parameter(ParameterSetName="Q", mandatory=$true)]
[Alias('q')]
[int]$query,
[Parameter(ParameterSetName="Q")]
[object[]]$arg
)
In this way you can't call function using only -arg
parameter, you need call -query
also.
$arg
accept an array, you can input your hostvals separed by commas. If you want values separed by spaces you can declare [string]$arg
and pass value in quotes, but you need to add some logic ( split
on spaces and so o on...) to make input usefull inside the script.
For adding custom help to your scripts read here http://blogs.technet.com/b/heyscriptingguy/archive/2010/01/07/hey-scripting-guy-january-7-2010.aspx
Upvotes: 2