My Technical Notes

Thursday, 9 February 2017

PowerShell: Checking if `-Verbose` switch is specified

You must add the attribute `CmdletBinding` onto your function if you want to take advantage of the `-Verbose` switch.

In order to check if the `-Verbose` switch is specified, use the `$VerbosePreference` variable:


Function Test-Function { 
    [CmdletBinding()] 
    param() 
    
    $VerbosePreference -eq [Management.Automation.ActionPreference]::Continue 
} 

Calling `Test-Function -Verbose` will return `true` and without will return `false`.

`Verbose` is propagated to functions called within the function, therefore, in the following code, `Outer` called with `-Verbose` still returns `true` and `false` without. Therefore we do not have to propagate it ourselves.


Function Outer {
    [CmdletBinding()]
    param()

    Test-Function
}

No comments: