Quantcast
Channel: Windows PowerShell Forum
Viewing all articles
Browse latest Browse all 2562

Problem specifying a default value when using parameter sets in powershell

$
0
0

I'm currently in the process of writing a script that takes advantage of Powershells comment-based help and plan on using Get-Help from within the script itself. This will allow me to have a -Help parameter that then runs Get-Help against the script being run. I have defined a Param section with a parameter for Help which is a string that allows me to specify the Help required ("", Full, Detailed and Examples). I have set validation on the parameter for this also. The problem I have is that I want to be able to specify -Help on the command line with no value and have it use a default of an empty string. When I do this I get the following error:

PS > .\Test.ps1 -Help
C:\Test.ps1 : Missing an argument for parameter 'Help'. Specify a parameter of type 'System.String' and tr
y again.
At line:1 char:17
+ .\Test.ps1 -Help <<<<
    + CategoryInfo          : InvalidArgument: (:) [Test.ps1], ParameterBindingException
    + FullyQualifiedErrorId : MissingArgument,Test.ps1

PS >

It works if I use -Help ""

A sample showing the issue follows:

<#
.SYNOPSIS 
Sample code
#>
param ( [Parameter(Mandatory=$true,ParameterSetName="Backup")]
		[switch]$Backup,
		
		[Parameter(Mandatory=$true,ParameterSetName="Help")]
		[ValidateSet("","Full","Detailed","Examples")]
		[AllowEmptyString()]
		[string]
		# Specify Full, Detailed or Examples
		$Help = ""
)
switch ($PSCmdlet.ParameterSetName) {
	Backup {"Backup"}
	Help {
		switch ($Help) {
			Full {Get-Help $MyInvocation.MyCommand.Definition -Full}
			Detailed {Get-Help $MyInvocation.MyCommand.Definition -Detailed}
			Examples {Get-Help $MyInvocation.MyCommand.Definition -Examples}
			default {Get-Help $MyInvocation.MyCommand.Definition}
		}
	}
}
Am I missing something or is it a bug?

Viewing all articles
Browse latest Browse all 2562

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>