13

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

Angshuman Agarwal
  • 4,796
  • 7
  • 41
  • 89

1 Answers1

24

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
James Pogran
  • 4,279
  • 2
  • 31
  • 23