I have a situation in which I need to define custom defined error handlers for errors in param block. For instance I need the function to return an exit value of 1 if there are some errors inside the param block and also print out a custom defined error message.
Below is my code:
function test {
Param(
[string]$Name,
[int]$age
)
Begin {
$ErrorVar = 0
if (! $Name) {
Write-Host "Name is a mandatory parameter...please provide a value"
$ErrorVar = 1
}
if (! $age) {
Write-Host "Age is a mandatory parameter...please provide a value"
$ErrorVar = 1
}
}
Process {
if ($ErrorVar -eq 0) {
Write-Host "My name is $name and my age is $age"
}
}
End {
if ($ErrorVar -eq 1) {
return 1
} else {
return 0
}
}
}
The error handler works properly if I don't use any one of the arguments (Name, Age):
PS> $var = test Name is a mandatory parameter...please provide a value Age is a mandatory parameter...please provide a value PS> $var = test -Name Subhayan Age is a mandatory parameter...please provide a value
But the moment when I omit the value to the argument I come across a system defined error message and my error handler is not called:
PS> $var = test -Name -age 32
test : Missing an argument for parameter 'Name'. Specify a parameter of type
'System.String' and try again.
At line:1 char:13
+ $var = test -Name -age 32
+ ~~~~~
+ CategoryInfo : InvalidArgument: (:) [test], ParameterBindingException
+ FullyQualifiedErrorId : MissingArgument,test
How can I ensure that my custom defined error message is called every time there is any error in the param block, even in cases when I use the argument name but failed to supply a value.