1

Let's say I have the following function:

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 ...')

  }
  ...

I would like to avoid the need to declare @params once my parameters were already declared and set. It's possible to do it with Powershell ?

3
  • You could use $PsBoundParameters. Commented May 30, 2017 at 16:52
  • 1
    @BenH is right,Invoke-SqlConnection @PSBoundParameters Commented May 30, 2017 at 17:13
  • @BenH, Please make it as an answer and I will accept it :) Commented May 30, 2017 at 18:02

1 Answer 1

5

The parameters that are passed in are saved in the automatic variable $PSBoundParameters. This can then be used by your command by splatting this variable with @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 ...')
}
...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.