Reputation: 117
I am confused about how to do error handling in the case that a mandatory variable remains null.
function parse-com{
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$True)]
[string[]]$list
)
...
In this case if no argument is passed for $list then I am prompted for it, but if I just hit enter (pass a null to $list) then I throw an error. What I would rather do is throw a usage statement and/or exit gracefully. Example...
PS C:\Users\memyself> parse-com
cmdlet parse-com at command pipeline position 1
Supply values for the following parameters:
list[0]:
parse-com : Cannot bind argument to parameter 'list' because it is an empty array.
At line:1 char:1
+ parse-com
+ ~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [parse-com], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyArrayNotAllowed,parse-com
Upvotes: 2
Views: 3858
Reputation: 10034
When passing a $null
value, that satisfies the Mandatory
requirement. If you want the command then to fail prior to execution then you should use validation as @JeffZeitlin suggests.
It sounds like what you need to validate is that the value is not $null
nor is it an empty array. For which you could user [ValidateNotNullOrEmpty()]
function parse-com{
[CmdletBinding()]
Param (
[Parameter(Mandatory=$True)]
[ValidateNotNullOrEmpty()]
[string[]]$list
)
Upvotes: 5