且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

你如何支持 PowerShell 的 -WhatIf &- 确认调用其他 Cmdlet 的 Cmdlet 中的参数?

更新时间:2022-03-26 08:14:03

经过一些谷歌搜索后,我想出了一个很好的解决方案,用于将通用参数传递给被调用的命令.您可以使用 @ splatting 运算符来传递传递给您的命令的所有参数.例如,如果

After some googling I came up with a good solution for passing common parameters along to called commands. You can use the @ splatting operator to pass along all the parameters that were passed to your command. For example, if

Start-Service -Name ServiceAbc @PSBoundParameters

Start-Service -Name ServiceAbc @PSBoundParameters

位于您的脚本正文中,powershell 会将传递给您的脚本的所有参数传递给 Start-Service 命令.唯一的问题是,如果你的脚本包含一个 -Name 参数,它也会被传递,PowerShell 会抱怨你包含了 -Name 参数两次.我编写了以下函数来将所有常用参数复制到一个新字典中,然后将其删除.

is in the body of your script powershell will pass all the parameters that were passed to your script to the Start-Service command. The only problem is that if your script contains say a -Name parameter it will be passed too and PowerShell will complain that you included the -Name parameter twice. I wrote the following function to copy all the common parameters to a new dictionary and then I splat that.

function Select-BoundCommonParameters
{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        $BoundParameters
    )
    begin
    {
        $boundCommonParameters = New-Object -TypeName 'System.Collections.Generic.Dictionary[string, [Object]]'
    }
    process
    {
        $BoundParameters.GetEnumerator() |
            Where-Object { $_.Key -match 'Debug|ErrorAction|ErrorVariable|WarningAction|WarningVariable|Verbose' } |
            ForEach-Object { $boundCommonParameters.Add($_.Key, $_.Value) }

        $boundCommonParameters
    }
}

最终结果是您将 -Verbose 之类的参数传递给脚本中调用的命令,它们会尊重调用者的意图.

The end result is you pass parameters like -Verbose along to the commands called in your script and they honor the callers intention.