2017-05-30 16 views
1

比方說,我有以下功能:如何在Powershell上重用param?

function Get-DBStatus 
{ 
    <# .. removed help section for brevity .. #> 
    [CmdletBinding()] 
    [OutputType([System.Object])] 
    param 
    (
    [Parameter(Mandatory = $true)] 
    [String]$ServerName, 
    [Parameter(Mandatory = $true)] 
    [String]$ServerUser, 
    [Parameter(Mandatory = $true)] 
    [String]$ServerPassword, 
    [Parameter(Mandatory = $true)] 
    [String]$DatabaseName, 
) 

    try 
    { 
    $params = @{ ... } # <<< It's possible to avoid this duplication ? 
    $dbStatus = Invoke-SqlConnection @params 
    } 
    catch 
    { 
    Write-Error -Message ('An error has occured while ...') 

    } 
    ... 

我想避免需要申報@params一旦我的參數已經被定義和設置。 Powershell可以做到這一點嗎?

+0

您可以使用'$ PsBoundParameters'。 – BenH

+1

@BenH是對的,'Invoke-SqlConnection @ PSBoundParameters' –

+0

@BenH,請把它作爲答案,我會接受它:) –

回答

5

傳入的參數保存在自動變量$PSBoundParameters中。然後,您可以使用@PSBoundParameters對此變量進行濺射來使用此命令。

function Get-DBStatus { 
    <# .. removed help section for brevity .. #> 
    [CmdletBinding()] 
    [OutputType([System.Object])] 
    param (
     [Parameter(Mandatory = $true)] 
     [String]$ServerName, 
     [Parameter(Mandatory = $true)] 
     [String]$ServerUser, 
     [Parameter(Mandatory = $true)] 
     [String]$ServerPassword, 
     [Parameter(Mandatory = $true)] 
     [String]$DatabaseName, 
    ) 

try { 
    $dbStatus = Invoke-SqlConnection @PSBoundParameters 
} 
catch { 
    Write-Error -Message ('An error has occured while ...') 
} 
... 
+0

謝謝你BenH! –

相關問題