functionpowershellparametersvariadic-functions

PowerShell pass all parameters received in function, and handle parameters with spaces


I am a novice with PowerShell. In Msys2 (or Lnux), I have defined a function npp

npp ()
{
    ${NPP_PATH} "$@"
}

such that if I call from the command prompt npp it launches Notepad++ (as defined in ${NPP_PATH}). If I call npp "mydir/stage 1/a.txt" it opens that file for editing. Generally speaking, it allows:

  1. Any number of parameters.
  2. Parameters containing spaces, if suitably escaped.

What would be the equivalent in PowerShell?

I guess in PS I should also go for a function to obtain a similar behavior. So far, I could receive an undefined number of parameters, and use them in a foreach loop, see code below. But I could not find the equivalent of the simple "$@" to pass all parameters as they are received. Moreover, if I use quotes in one of the arguments, they are removed, so it will probably have problems with file paths including blanks.

function multi_params {
    param(
        [Parameter(
            ValueFromRemainingArguments=$true
        )][string[]]
        $listArgs
    )
    $count = 0
    foreach($listArg in $listArgs) {
        '$listArgs[{0}]: {1}' -f $count, $listArg
        $count++
    }
}

Solution

  • Assuming that NPP_PATH is an environment variable, the equivalent PowerShell function is:

    function npp {
      & $env:NPP_PATH $args
    }
    

    If NPP_PATH is the name of a regular PowerShell variable, use & $NPP_PATH $args.

    & is the call operator, which is needed for syntactic reasons whenever you want to invoke a command whose name/path is specified in quotes and/or via a variable.

    In simple functions (as opposed to advanced functions) such as the above (use of neither [CmdletBinding()] nor [Parameter()] attributes), you can use the automatic $args variable to pass any arguments through to another command.


    Passing arguments through in simple vs. advanced functions (scripts):


    The automatic $PSBoundParameters variable is a dictionary that is available in both simple and advanced functions:


    [1] That type is [System.Collections.Generic.List[object]]; however, you can specify a collection type explicitly, such as [object[]] to get a regular PowerShell array.