powershellparameter-passingargs

PowerShell : args and named parameter


I have a PS script I call from a Windows shortcut. I drop on it several files or directories, and it works fine. I would like to add some named parameters (let's call them : -Param1 and -Param2), optional, that can be used, of course, only from PowerShell Prompt.

param (
    [switch]$CreateShortcut
)

A switch parameter works.

But, if I add a string parameter :

param (
    [switch]$CreateShortcut,
    [string]$Param1
)

Of course, it does not work anymore when I call my script thru the Windows shortcut : $Param1 receive the first file.

Is there a solution ?

Thanks


Solution

  • When you drop files/folders on a shortcut file, their full paths are passed as individual, unnamed arguments to the shortcut's executable (script).

    PowerShell allows you to collect such unnamed arguments in a single, array-valued parameter, by declaring it as ValueFromRemainingArguments:

    [CmdletBinding(PositionalBinding=$false)]
    param (
        [switch] $CreateShortcut,
        # Collect all unnamed arguments in this parameter:
        [Parameter(ValueFromRemainingArguments)]
        [string[]] $FilesOrFolders
    )