4

I need a little help on how I can enforce the following constraints on the arguments to a powershell script. Can I specify these constraints with in the param section.

  1. At least one argument constraint
  2. At most one argument constraint

For example, (just an example, it's not what I am doing) to a script called ReadPlainText.ps1, I would like to give only either of the two arguments: Lines or Chars, but not both. The command ReadPlainText.ps1 Sample.txt -Lines 20 -Chars 10 should result in an error. Similarly, the command ReadPlainText.ps1 Sample.txt should result in error.

2 Answers 2

6

You can, in PSH V2, do this will parameter attributes and by putting the two parameters into different parameter sets.

A parameter set is a group of parameters that go together, a command can have multiple parameter sets and only one is available. Parameters not assigned to a parameter group are available across all parameters. This can be seen in the standard cmdlets (removing the common parameters):

PS> gcm -syn get-content

Get-Content [-Path]  …
Get-Content [-LiteralPath]  …

To achive this in a script or function:

  • Add [CmdletBinding] as the first non-comment. (A default parameter set can be specified here.)
  • In the param block decorate parameters with the Parameter attribute to specify mandatory and the parameter set.

Thus:

[CmdletBinding]
param (
  [parameter(mandatory=$true,ParameterSetName='lines')
  [int]$Lines,
  [parameter(mandatory=$true,ParameterSetName='chars')
  [int]$|Chars
)

To access the parameter set in use $PSCmdlet which gives access to the same information available within cmdlets written C# or VB.

Sign up to request clarification or add additional context in comments.

3 Comments

Please correct mandator=$true to mandatory=$true, i do not have edit rights
@oleschri Done. You could always suggest an edit, they get approved (or rejected) pretty quickly.
I know, but SO requires at least 6 changed characters to do so ... ;)
2

This Example (Source: PowerShell Script – Marking a parameter as required/optional) might help you ...

param(
      [string] $param1 = $(throw "required param"), #throw exception if no value provided.
      [string] $param2, #an optional parameter with no default value.
      [string] $param3 = "default value", #an optional parameter with a default value.
      [string] $param4 = $(Read-Host -prompt "param4 value"), #prompt user for value if none provided.
      [string] $param5 = $( if($thisinput -eq "somevalue") { "defaultvalue1" } else { "defaultvalue2" } ) #conditional default value  
      )

1 Comment

Valid maybe for V1. Don't use for V2, parameter sets are designed for this purpose.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.