假设我有以下功能:
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 :(得分: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 ...')
}
...