使用PowerShell会话变量作为参数的默认值

时间:2016-10-05 13:18:18

标签: powershell powershell-v4.0

可以使用存储在PowerShell会话变量中的值来填充参数的默认值吗?

在此示例中,会话变量在第一次运行脚本时填充,但不会在后续执行中使用:

function Get-Authetication
{

    [cmdletbinding()]
    param(
        [parameter(Mandatory=$true)]
        [string]$Server = { if ($PSCmdlet.SessionState.PSVariable.Get('Server').Value) { $PSCmdlet.SessionState.PSVariable.Get('Server').Value } },

        [parameter(Mandatory=$true)]
        [pscredential]$Credential = (Get-Credential)

    )

    # store
    $PSCmdlet.SessionState.PSVariable.Set('Server',$Server)
    $PSCmdlet.SessionState.PSVariable.Set('Credential',$Credential)

    # return for testing
    [PsCustomObject]@{
        Server=$PSCmdlet.SessionState.PSVariable.Get('Server').Value;
        Username=($PSCmdlet.SessionState.PSVariable.Get('Credential').Value).Username
    }
}

Get-Authetication

1 个答案:

答案 0 :(得分:2)

这应由来电者使用$PSDefaultParameterValues完成。

或者,在函数中执行此操作而不是使用默认值:

function Get-Authetication
{

    [cmdletbinding()]
    param(
        [parameter()]
        [string]$Server,

        [parameter()]
        [pscredential]$Credential = (Get-Credential)

    )
    if (!$PSCmdlet.SessionState.PSVariable.Get('Server').Value -and !$Server) {
        $Server = Read-Host 'Enter server'
        # Alternatively
        # throw [System.ArgumentException]'You must supply a Server value'
    }
    if ($Server) {
        $PSCmdlet.SessionState.PSVariable.Set('Server',$Server)
    }
    $myServer = $PSCmdlet.SessionState.PSVariable.Get('Server').Value

    # return for testing
    [PsCustomObject]@{
        Server=$myServer;
    }
}

(缩写示例)