Powershell: defining a Verbose switch in a function

We are sending this link, I am trying to enter a 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 named "Verbose" has been defined for some time for the command. On line: 12 char: 9 + Get-Help <<<<TestVerbose + CategoryInfo: MetadataError: (:) [Get-Help], MetadataException + FullyQualifiedErrorId: ParameterNameAlreadyExistsForCommand, Microsoft.PowerShell.Commands.GetHelpCommand

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

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

Any idea why this behavior? I want to keep the required switch and want the user to execute my function as follows:

TestVerbose -verbose

+8
powershell
source share
1 answer

It looks like you are using PoweShell v2 in which Verbose is reserved (along with debug, whatif, etc.) and their functions are automatically provided for you. Instead of writing your own β€œverbose” discovery switch, functionality already exists. In the case of detail, you do not need to specify it in the parameter declaration, other parameters like 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 
+16
source share

All Articles