Powershell嵌套函数和参数问题

时间:2018-10-04 16:35:23

标签: powershell powershell-v2.0 powershell-v3.0

我正在尝试具有两个主要功能,您可以将其他功能传递给这些功能。例如

./ script.ps1-本地test1,test2

这是我的代码,-local可以正常工作,并且在之后也要求其他输入,但实际上并没有输出test1。

def __str__(self):

    num_decimal_places = 3

    def write_coefficient( coefficient, is_initial_term=False):
        coefficient = round(coefficient , num_decimal_places)

        if coefficient % 1 == 0:
            coefficient = int (coefficient)

        output = ''

        if coefficient < 0:
            output += '-'
        if coefficient > 0 and not is_initial_term:
            output += '+'

        if not is_initial_term:
            output += ' '

        if abs(coefficient) != 1:
            output += '{}'.format(abs(coefficient))

        return output

    n = self.normal_vector

    try:
        initial_index = Plane.first_nonzero_index(n.coordinates)
        terms = [write_coefficient(n.coordinates , is_initial_term=(i==initial_index)) + 'x_{}'.format(i+1)
                 for i in range(self.dimension) if round(n.coordinates , num_decimal_places) != 0]
        output = ' '.join(terms)

    except Exception as e:
        if str(e) == self.NO_NONZERO_ELTS_FOUND_MSG:
            output = '0'
        else:
            raise e

    constant = round(self.constant_term, num_decimal_places)
    if constant % 1 == 0:
        constant = int(constant)
    output += ' = {}'.format(constant)

    return output

1 个答案:

答案 0 :(得分:0)

不太确定您要完成什么,但是我认为这可以使您前进:

[CmdletBinding(DefaultParameterSetName='default')]
Param(
    [Parameter(ParameterSetName='default', Position=0, Mandatory=$true)]
    [string[]]$Default,

    [Parameter(ParameterSetName='external', Position=0, Mandatory=$true)]
    [string[]]$External,

    [Parameter(ParameterSetName='local', Position=0, Mandatory=$true)]
    [switch]$Local,

    [Parameter(ParameterSetName='local', Position=1, Mandatory=$false)]
    [ValidateSet ('Test1','Test2')]
    [string]$ExecuteLocal = 'Test1'
)

function RunLocal {
    [CmdletBinding()]
    Param(
        [Parameter(Position=0, Mandatory=$false)]
        [ValidateSet ('Test1','Test2')]
        [string]$Execute = 'Test1'
    )

    function Test1 {Write-Host 'Running Local -> Test1'}
    function Test2 {Write-Host 'Running Local -> Test2'}

    switch ($Execute) {
        'Test1'  { Test1 }
        'Test2'  { Test2 }
    }
}

function RunExternal {Write-Host 'Running External'}
function RunDefault  {Write-Host 'Running Default'}

switch ($PSCmdlet.ParameterSetName) {
    'local'    { RunLocal -Execute $ExecuteLocal }
    'external' { RunExternal }
    'default'  { RunDefault }
}

如您所见,我已经向本地函数添加了ValidateSet,因此您可以将其用作说明Test1Test2的参数。

此外,在功能RunLocal中,我将内部功能放在了开关上方,因为在Powershell中需要先定义功能,然后才能调用它们。

使用./script.ps1 -Local -ExecuteLocal Test1

运行它

希望这会有所帮助