Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: Defining the Verbose switch in a function

Referring this link, I am trying to introduce verbose mode in my script.

When I have a function defined like this -

function TestVerbose
{
    param(
        [switch]$verbose,
        [Parameter(Mandatory = $True)] 
        $p1
    )

    if($verbose)
    {
     Write-Verbose "Verbose Mode"
    }
}

Get-Help TestVerbose

I get the following error -

Get-Help : A parameter with the name 'Verbose' was defined multiple times for the command. At line:12 char:9 + Get-Help <<<< TestVerbose + CategoryInfo : MetadataError: (:) [Get-Help], MetadataException + FullyQualifiedErrorId : ParameterNameAlreadyExistsForCommand,Microsoft.PowerShell.Commands.GetHelpCommand

BUT, if I define the function like this [removing the parameter mandatory attribute], it works fine

function TestVerbose
{
    param(
        [switch]$verbose,
        $p1
    )
    if($verbose)
    {
     Write-Verbose "Verbose Mode"
    }    
}

Get-Help TestVerbose

Any idea why such a behaviour ? I want to keep the mandatory switch and want the user to execute my function like this -

TestVerbose -verbose

like image 521
Angshuman Agarwal Avatar asked May 10 '12 14:05

Angshuman Agarwal


1 Answers

It appears you are using PoweShell v2, in which Verbose (along with debug, whatif, etc) are reserved and their functions automatically provided for you. Instead of writing your own 'verbose' detection switch, the functionality is already there. In the case of verbose you don't have to specify it in the parameter declaration, other parameters likes whatif require special synatax.

C:\Users\james> function testverbose{
>>     param(
>>         [Parameter(Mandatory = $True)]
>>         $bar
>>     )
>>
>>     Write-Verbose "VERBOSE!"
>>     $bar
>> }
>>
C:\Users\james> testverbose -bar "woot"
woot
C:\Users\james> testverbose -bar "woot" -Verbose
VERBOSE: VERBOSE!
woot
like image 151
James Pogran Avatar answered Nov 16 '22 02:11

James Pogran