gpt4 book ai didi

powershell - 如何在Powershell上重用参数?

转载 作者:行者123 更新时间:2023-12-03 00:34:57 24 4
gpt4 key购买 nike

假设我具有以下功能:

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做到吗?

最佳答案

传入的参数保存在自动变量$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 ...')
}
...

关于powershell - 如何在Powershell上重用参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44267631/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com