Just by running the “test” function as you have it, you get the below error:
test : Cannot validate argument on parameter 'ComputerName'. The number of provided arguments, (8), exceeds the maximum number of allowed arguments (5). Provide fewer than 5
arguments, and then try the command again.
At line:10 char:20
+ test -ComputerName 1,2,3,4,5,6,7,8
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [test], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,test
It looks like you’re planning to call your “test” function inside of a script or function. You can do the following. You’ll need to turn the script/function that’s got the below Try/Catch blocks in by adding [CmdletBinding()] at the top.
Try
{
test -ComputerName 1,2,3,4,5,6,7,8 -ErrorAction Stop
}
Catch [System.Management.Automation.ValidationMetadataException]
{
Write-Warning "$($_.Exception.Message)"
}
You get:
WARNING: Cannot validate argument on parameter 'ComputerName'. The number of provided arguments, (8), exceeds the maximum number of allowed arguments (5). Provide fewer than 5 arguments, and then try the command again.
Personally, I like the above details, but if you really want to write you own warning details, you can use the -split operator to split exception message on the comma (,), grab the right string object, & trim the space and parenthesis off to get the number 8.
$ComputerNameQuantitySupplied = ($($_.Exception.Message -split ",")[1].Trim()).Trim("()")