默认情况下,任何具有 [CmdletBinding()] 属性的命名函数都接受 -debug
和 -verbose
(以及其他一些)参数,并具有预定义的$debug
和 $verbose
变量。我正在尝试弄清楚如何将它们传递给在函数内调用的其他 cmdlet。
假设我有一个如下所示的 cmdlet:
function DoStuff() {
[CmdletBinding()]
PROCESS {
new-item Test -type Directory
}
}
如果 -debug
或 -verbose
已传递到我的函数中,我想将该标志传递到 new-item
cmdlet 中。这样做的正确模式是什么?
最佳答案
$PSBoundParameters
不是您要查找的内容。除了提供 Verbose 标志之外,使用 [CmdletBinding()]
属性还允许在脚本中使用 $PSCmdlet
。事实上,您应该使用同样的详细信息。
通过[CmdletBinding()]
,您可以通过$PSCmdlet.MyInitation.BoundParameters
访问绑定(bind)的参数。这是一个使用 CmdletBinding 的函数,只需立即输入嵌套提示即可检查函数作用域内可用的变量。
PS D:\> function hi { [CmdletBinding()]param([string] $Salutation) $host.EnterNestedPrompt() }; hi -Salutation Yo -Verbose
PS D:\>>> $PSBoundParameters
____________________________________________________________________________________________________
PS D:\>>> $PSCmdlet.MyInvocation.BoundParameters
Key Value
--- -----
Salutation Yo
Verbose True
<小时/>
因此,在您的示例中,您需要以下内容:
function DoStuff `
{
[CmdletBinding()]
param ()
process
{
new-item Test -type Directory `
-Verbose:($PSCmdlet.MyInvocation.BoundParameters["Verbose"].IsPresent -eq $true)
}
}
这涵盖了 -Verbose、-Verbose:$false、-Verbose:$true 以及根本不存在该开关的情况。
关于powershell - 如何在自定义 cmdlet 中正确使用 -verbose 和 -debug 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4301562/