powershell - 如何在自定义 cmdlet 中正确使用 -verbose 和 -debug 参数

标签 powershell parameters powershell-cmdlet

默认情况下,任何具有 [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/

相关文章:

powershell - DISKPART 与 PowerShell 获取卷

powershell - 在Powershell中通过管道(|)传递 “string”变量不起作用

parameters - 如何将创建参数传递给抽象?

c# - 通过代码添加 Entity Framework 迁移

c#-4.0 - 如何安全地处理自定义编写的 PowerShell cmdlet 中的密码?

c# - 如何验证 PowerShell cmdlet 中的相关参数

powershell - Powershell:过滤事件日志

powershell - 脚本在 ISE 中运行,而不是在某些 powershell CLI 中运行

c - 如何修改已传递给 C 函数的指针?

java - Android Camera.Parmaters 中的 fast-fps-mode - 如何访问和更改?