问题描述
我有一个支持 -WhatIf
的 PowerShell 脚本 cmdlet &-确认
参数.
I have a PowerShell script cmdlet that supports the -WhatIf
& -Confirm
parameters.
它通过在执行更改之前调用 $PSCmdlet.ShouldProcess()
方法来实现这一点.
这按预期工作.
It does this by calling the $PSCmdlet.ShouldProcess()
method before performing the change.
This works as expected.
我遇到的问题是我的 Cmdlet 是通过调用其他 Cmdlet 实现的,并且 -WhatIf
或 -Confirm
参数没有传递给我调用的 Cmdlet.
The problem I have is that my Cmdlet is implemented by calling other Cmdlets and the -WhatIf
or -Confirm
parameters are not passed along to the Cmdlets I invoke.
如何将 -WhatIf
和 -Confirm
的值传递给从 Cmdlet 调用的 Cmdlet?
How can I pass along the values of -WhatIf
and -Confirm
to the Cmdlets I call from my Cmdlet?
例如,如果我的 Cmdlet 是 Stop-CompanyXyzServices
并且它使用 Stop-Service
来实现其操作.
For example, if my Cmdlet is Stop-CompanyXyzServices
and it uses Stop-Service
to implement its action.
如果 -WhatIf
被传递给 Stop-CompanyXyzServices
我希望它也被传递给 Stop-Service.
If -WhatIf
is passed to Stop-CompanyXyzServices
I want it to also be passed to Stop-Service.
这可能吗?
推荐答案
经过一些谷歌搜索后,我想出了一个很好的解决方案,用于将通用参数传递给被调用的命令.您可以使用 @ 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.
这篇关于你如何支持 PowerShell 的 -WhatIf &- 确认调用其他 Cmdlet 的 Cmdlet 中的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!