Hi big and all-knowing ALL.
I have PS script that uses named parameters. Something like:
param (
[switch]$help
)
function Usage
{
write-host "Usage:"
exit 1
}
if ($help){ Usage }
If I invoke it like: myScript.ps1 --help
everything works fine - I get usage.
If I invoke it without parameters - it also is Ok - I get nothing.
Problem occurs when I invoke it with total wrong parameter. For example :
myScript.ps1 --kuku
or myScript.ps1 kuku
In this case “param” section simply ignore parameter, that does not suit its definitions.
Of cause I can abandon “param” section and switch to primitive loop over @args array and manual parsing of arguments. This way I can for sure discover that user entered unsupported argument.
But question is - do PS have more elegant way to do such validation?
I believe - it have to have something that do it, since problem seems to be fairly common. But I can not find anything that suite this task…
Hi Tony
I have used [CmdletBinding()] and it generally do what I need.
But I face 2 problems - that I do not success to solve.
If I pass wrong parameter - PS throws error message about it (as expected ) and stops execution of script. Good! But I did not success to find a way to customize this error message. Is it possible?
In case of wrong parameter - exit code of script is - 0. Can I change it somehow to be for example - 1? So - caller script/batch will “know” that something gone wrong?
I would encourage you to investigate the link on Comment Based Help posted by matt-bloomfield. There really is no reason to write code for help when that functionality is built into PowerShell.
Hi Darwin. Generally I agree with you.
But I have pre-defined requirement, that in case of wrong command-line parameters script will exit with exit code 1.
And default behavior, pre-scribed by use of CmdletBinding - exit code is - 0.
Although - you get err-message about wrong parameter, but exit code of script is - 0
In this case your powershell.exe command completes successfully, so the exit code would be 0. If it has an error itself it will return an error. I remember reading something about this but can’t find it at the moment. In the meantime, I’d check $lastexitcode it code in your script itself.