In powershell, is it possible to use argument naming?

Given a script foo.ps1: param ($ x, $ y) returns $ x / $ y

Is it possible to force an explicit parameter name when invoked?

./foo.ps1 5 10 generates an error. /foo.ps1 -x 5 -y 10 will be OK

+4
source share
4 answers

This code works, but it uses something that is not documented (I could not find anything about negative positions):

function Test
{
    param(
        [Parameter(Position=-1)]
        $x
        ,
        [Parameter(Position=-1)]
        $y
    )
    $x/$y
}

Test -x 1 -y 2
Test -y 2 -x 1
Test 1 2

Conclusion:

0.5
0.5
Test : Cannot bind positional parameters because no names were given.
At C:\TEMP\_110127_170853\q1.ps1:15 char:5
+4
source

If you specify a position using the position property of the leading PowerShell V2 function, all default parameters will be non-positional unless the position property is set for other parameters (source: PowerShell In Action 2nd pg 296). So you can do this:

function Test-Args
{
    param(
    [parameter(Position=0)] $dummy,
    $x,
    $y
    )
    $x/$y
}
+4
source

You can specify this in the CmdletBinding argument. Even if PositionalBinding is set to $ false, you can still assign positions to your parameters. PowerShell will no longer automatically assign positions to your options, so all options are named unless otherwise specified.

function foo {
    [CmdletBinding(PositionalBinding=$false)]

    param (

        [Parameter()]
        [String]$a,

        [Parameter(Position=0)]
        [String]$a,
    )
}
+1
source

I am going to go with this for foo.ps1. If someone fails to explicitly use -dummy1 or -dummy2 to specify arguments, it should work fine.

param($dummy1,$x,$y,$dummy2)
if (!$x -or !$y -or $dummy1 -or $dummy2){
"Error: specify -x and -y explicitly"
}
else {$x/$y}
0
source

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


All Articles