Q:

Positional parameter binding with values starting with a minus/hyphen

Here is my PowerShell test script:
param( 
   [Parameter(Mandatory=$true,
              Position=0)]
   [int]$val
)
Write-Output $val;

Now I want to call it like this:
Powershell -ExecutionPolicy Bypass -File ".\testscript.ps1" "-1"

The error I get is:

A parameter cannot be found that matches parameter name '1'.

Note that I have no control over the way the application calls my script (i.e. I can not make the application call my script with -val:-1). So binding has to be positional. How can I make my script bind -1 to $val with the param block?

A:

If you can't fix how the application calls the script the only other option I see is to drop the named parameters entirely and use the $args collection instead:
C:\>type test.ps1
[int]$val = $args[0]
Write-Output $val

C:\>powershell -ExecutionPolicy Bypass -File test.ps1 -1
-1
By casting the argument to [int] type safety is still enforced:
C:\>powershell -ExecutionPolicy Bypass -File test.ps1 a
Cannot convert value "a" to type "System.Int32". Error: "Input string was not
in a correct format."
At C:\Users\cobalt\Documents\test\test.ps1:1 char:1
+ [int]$val = $args[0]
+ ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : MetadataError: (:) [], ArgumentTransforma...
    + FullyQualifiedErrorId : RuntimeException

