How to properly use the -verbose and -debug parameters in a custom cmdlet

前端 未结 8 677
庸人自扰
庸人自扰 2020-12-13 04:08

By default, any named function that has the [CmdletBinding()] attribute accepts the -debug and -verbose (and a few others) parameters and has the p

8条回答
  •  情歌与酒
    2020-12-13 04:49

    $PSBoundParameters isn't what you're looking for. The use of the [CmdletBinding()] attribute allows the usage of $PSCmdlet within your script, in addition to providing a Verbose flag. It is in fact this same Verbose that you're supposed to use.

    Through [CmdletBinding()], you can access the bound parameters through $PSCmdlet.MyInvocation.BoundParameters. Here's a function that uses CmdletBinding and simply enters a nested prompt immediately in order examine the variables available inside the function scope.

    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                                                                                       
    

    So in your example, you would want the following:

    function DoStuff `
    {
        [CmdletBinding()]
        param ()
        process
        {
          new-item Test -type Directory `
            -Verbose:($PSCmdlet.MyInvocation.BoundParameters["Verbose"].IsPresent -eq $true)
        }
    }
    

    This covers -Verbose, -Verbose:$false, -Verbose:$true, and the case where the switch is not present at all.

提交回复
热议问题