如何在Powershell上重用param?

时间:2017-05-30 16:38:12

标签: powershell

假设我有以下功能:

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可以做到这一点吗?

1 个答案:

答案 0 :(得分: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 ...')
}
...