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

前端 未结 8 672
庸人自扰
庸人自扰 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:45

    Here's my solution:

    function DoStuff {
        [CmdletBinding()]
        param ()
    
        BEGIN
        {
            $CMDOUT = @{
                Verbose = If ($PSBoundParameters.Verbose -eq $true) { $true } else { $false };
                Debug = If ($PSBoundParameters.Debug -eq $true) { $true } else { $false }
            }
    
        } # BEGIN ENDS
    
        PROCESS
        {
            New-Item Example -ItemType Directory @CMDOUT
        } # PROCESS ENDS
    
        END
        {
    
        } #END ENDS
    }
    

    What this does different from the other examples is that it will repsect "-Verbose:$false" or "-Debug:$false". It will only set -Verbose/-Debug to $true if you use the following:

    DoStuff -Verbose
    DoStuff -Verbose:$true
    DoStuff -Debug
    DoStuff -Debug:$true
    

提交回复
热议问题