I would like -h without passing a value to work as well as -h with a parameter:
However, I would like the others to remain how they are… That is, they are optional, unless you alias a parameter and you are required to supply a value.
Param(
$BadParam,
[alias("h")][String]$Help,
[alias("s")][String]$Server,
[alias("d")][String]$DocRoot,
[alias("c")][String]$Commit,
[alias("b")][String]$Branch
)
For example (for lack of better):
if(!$Help)
{
Write-Host "Here's the menu for how it works bro."
}
if($Help)
{
Write-Host "Here's more info on that particular thing from the menu."
}
How I would expect this to behave in shell:
-> script.ps1 -s test -h
-> Here's the menu for how it works bro.
-> script.ps1 -s test -h server
-> Here's more info on that particular thing from the menu.
-> script.ps1 -s -h server
-> You are missing a value for -e.
Powershell doesn’t really support something like this. You can have a
[switch]parameter which can be specified with no value, or you can have a[string]parameter which must either be completely absent, or provided with a value. You can’t have a parameter which supports being absent, specified with no value, and specified with a value.One alternative is the make it a
[string], but have users pass$null, but that kind of sucks.Another extremely hacky alternative is the do some trickery with parameter positions.
-Helpcould be a[switch], then there could be another parameter-ThingHelppositioned right after it which is a[string]. Then an invocation which looks like-Help 'foo'is not setting$Helpto'foo'but rather setting the$Helpswitch, and also assigning$ThingHelp = 'foo'.This supports the following:
Hacks like this are not a good idea in general, since they tend to be both fragile and confusing. You should be able to give you scripts to an average powershell user, and they should immediately understand the meaning and usage of your parameters. If you have to explain a bunch of custom stuff that none of the thousands of other cmdlets out there are doing, you’re probably wasting everyone’s time.
And if you are literally implementing some kind of help/usage system, please stop! Powershell provides a comprehensive help system for free. You can document every parameter, give example code, etc, without anything extra. See documentation for comment-based help.