PowerShell : use parameter validation without throwing exception PowerShell : use parameter validation without throwing exception powershell powershell

PowerShell : use parameter validation without throwing exception


So okay, it is not possible to use param AND to catch the related exceptions.


The examples are for functions (simple and advanced) but the same idea should work for scripts with param as well:

# Simple function.# Everything not declared in `param` goes to $args.# If $args is not empty then there are "invalid" parameters or "unexpected" argumentsfunction test {    param (        [string]$path,        [int]$days,        [int]$hours    )    # check $args and throw an error (in here we just write a warning)    if ($args) { Write-Warning "Unknown arguments: $args" }}

Or

# Advanced function.# For an advanced function we can use an extra argument $args# with an attribute `[Parameter(ValueFromRemainingArguments=$true)]`function test {    param (        [Parameter(Mandatory=$true )] [string] $path,        [Parameter(Mandatory=$false)] [int]    $days,        [Parameter(Mandatory=$false)] [int]    $hours,        [Parameter(ValueFromRemainingArguments=$true)] $args    )    # check $args and throw an error (in this test we just write a warning)    if ($args) { Write-Warning "Unknown arguments: $args" }}

The following test:

# invalid parametertest -path p -invalid -days 5# too many argumentstest -path p 5 5 extra

in both cases produces the same output:

WARNING: Unknown arguments: -invalidWARNING: Unknown arguments: extra


A possible workaround is to wrap your actual function in another one. Something similar to a private/public relation. Example:

function Example-Private{    [CmdletBinding()]    Param    (        [ValidateNotNullOrEmpty()]        [string]$Arg1,        [ValidateNotNullOrEmpty()]        [string]$Arg2      )   # Do what you need}function Example-Public{    [CmdletBinding()]    Param    (        [string]$Arg1,        [string]$Arg2       )    try    {       Example-Private $Arg1 $Arg2    }    catch    {       # Display a user-friendly message, save exception into a log file, etc.    }}

If you are working on a module you could take a look here how to export your public functions and hide the private ones: Export Powershell Functions