开发者

In powershell, is it possible to enforce naming of arguments?

开发者 https://www.devze.com 2023-02-06 21:11 出处:网络
Given a script foo.ps1: param($x,$y) return $x/$y Is it possible to enforce explicit parameter naming when calling it?

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

Is it possible to enforce explicit parameter naming when calling it?

./foo.ps1 5 10 would generate an error ./foo.ps1 开发者_如何学Python-x 5 -y 10 would be OK


This code works but it uses something 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

Output:

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


If you specify a position using the PowerShell V2 advance function position property all parameters default to non-positional unless a position property is specified for other parameters (source: PowerShell In Action 2nd pg 296). So you could do this:

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


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

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

    param (

        [Parameter()]
        [String]$a,

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


I'm going to go with this for foo.ps1. Unless somebody manages to explicitly use -dummy1 or -dummy2 to specify the 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

精彩评论

暂无评论...
验证码 换一张
取 消