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

前端 未结 8 670
庸人自扰
庸人自扰 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 05:08

    There is no need. PowerShell already does this as the code below proves.

    function f { [cmdletbinding()]Param()    
        "f is called"
        Write-Debug Debug
        Write-Verbose Verbose
    }
    function g { [cmdletbinding()]Param() 
        "g is called"
        f 
    }
    g -Debug -Verbose
    

    The output is

    g is called
    f is called
    DEBUG: Debug
    VERBOSE: Verbose
    

    It is not done as direct as passing -Debug to the next cmdlet though. It is done through the $DebugPreference and $VerbrosePreference variables. Write-Debug and Write-Verbose act like you would expect, but if you want to do something different with debug or verbose you can read here how to check for yourself.

    0 讨论(0)
  • 2020-12-13 05:09

    Perhaps it sounds strange, but there isn't any easy way for a cmdlet to know its verbose or debug mode. Take a look at the related question:

    How does a cmdlet know when it really should call WriteVerbose()?

    One not perfect, but practically reasonable, option is to introduce your own cmdlet parameters (for example, $MyVerbose and $MyDebug) and use them in the code explicitly:

    function DoStuff {
        [CmdletBinding()]
        param
        (
            # Unfortunately, we cannot use Verbose name with CmdletBinding
            [switch]$MyVerbose
        )
    
        process {
    
            if ($MyVerbose) {
                # Do verbose stuff
            }
    
            # Pass $MyVerbose in the cmdlet explicitly
            New-Item Test -Type Directory -Verbose:$MyVerbose
        }
    }
    
    DoStuff -MyVerbose
    

    UPDATE

    When we need only a switch (not, say, a verbosity level value) then the approach with $PSBoundParameters is perhaps better than proposed in the first part of this answer (with extra parameters):

    function DoStuff {
        [CmdletBinding()]
        param()
    
        process {
            if ($PSBoundParameters['Verbose']) {
                # Do verbose stuff
            }
    
            New-Item Test -Type Directory -Verbose:($PSBoundParameters['Verbose'] -eq $true)
        }
    }
    
    DoStuff -Verbose
    

    It's all not perfect anyway. If there are better solutions then I would really like to know them myself.

    0 讨论(0)
提交回复
热议问题