Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Print all positional arguments in PowerShell

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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#.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading