Powershell constraints on arguments

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

  • At least one argument constraint
  • Maximum argument limit

For example (for example, this is not what I am doing) with a script called ReadPlainText.ps1 , I would like to specify only one of two arguments: Lines or Chars , but not both. The ReadPlainText.ps1 Sample.txt -Lines 20 -Chars 10 should result in an error. Similarly, the ReadPlainText.ps1 Sample.txt should result in an error.

+4
source share
2 answers

In PSH V2, you can do this with parameter attributes and put two parameters in different parameter sets.

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

  PS> gcm -syn get-content

 Get-Content [-Path] ...
 Get-Content [-LiteralPath] ...

To achieve this in a script or function:

  • Add [CmdletBinding] as the first comment. (Here you can specify a set of default parameters.)
  • In the param block, decorate the parameters with the Parameter attribute to indicate the required and the set of parameters.

In this way:

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

To access the used parameter set $PSCmdlet , which provides access to the same information available in cmdlets written in C # or VB.

+6
source

This example ( Source: PowerShell Script - Parameter Labeling as Required / Optional ) may 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 ) 
+2
source

Source: https://habr.com/ru/post/1344914/


All Articles