Home > Net >  Print all positional arguments in PowerShell
Print all positional arguments in PowerShell

Time:11-04

I'm trying to write a PowerShell function that prints out all its arguments.

ArgChecker.ps1

function Print-Args
{
  [CmdletBinding()]
  param ([string[]]$words)
    Write-Verbose "Count: $($words.Count)"
    Write-Output "Passed arguments:"
    $words
}

I'd also like to call it from a command prompt.

I'm doing it like this

powershell -ExecutionPolicy Bypass -command "& { . .\ArgChecker.ps1; Print-Args 'hi' 'Two' -Verbose }"

but it is throwing an error Print-Args : A positional parameter cannot be found that accepts argument 'Two'.

Is there any way to write the function so that it can accept an unlimited amount of parameters in that format? I think I'm looking for something similar to the params keyword from C#.

CodePudding user response:

In regular functions, you can use the $args automatic variable.

function Write-Args {
    $args
}

If you need a cmdlet with CmdletBinding, you can use the ValueFromRemainingArguments option:

function Write-Args {
    [CmdletBinding()]
    param(
        [Parameter(ValueFromRemainingArguments)]
        [string[]]$Arguments
    )
    $Arguments
}

Note however, because of the CmdletBinding, -Verbose will not appear in that list, because it's a common parameter. If you want to list those too, you could use the $PSBoundParameters automatic variable.

  • Related