6

I have a PowerShell function that basically looks like this:

function DoSomething-ToTask {
    [cmdletbinding()]
    param(
          [parameter(Mandatory=$true)]
          [strehg[]]$TaskNums
    )

    foreach ($TaskNum in $TaskNums) {
        do something $TaskNum
    }
}

The goal is to be able to be able to call this function from the command line with an arbitrary number of parameters. For example, I may call it like this now:

DoSomething-ToTask 1 2 3

..and like this later

DoSomething-ToTask 4

The second example works, but the first one does not. I have since learned that I need to pass multiple arguments like this:

DoSomething-ToTask (1, 2, 3)

Which isn't the worst thing in the world but still kind of a pain compared to the first example.

Is there any way to write a PS function that works with the "1 2 3" argument example?

user229044
  • 232,980
  • 40
  • 330
  • 338
Tom Purl
  • 519
  • 4
  • 20
  • As an aside: you don't need the `(...)` around `1, 2, 3` - in fact, doing so would make the syntax more cumbersome if the array elements were _strings_ - see [this answer](https://stackoverflow.com/a/63162649/45375). – mklement0 Jul 30 '20 at 22:00

1 Answers1

12

Yes, you can use the ValueFromRemainingArguments parameter attribute.

function DoSomething-ToTask {
    [cmdletbinding()]
    param(
          [Parameter(Mandatory=$true, ValueFromRemainingArguments = $true)]
          [int[]]$TaskNums
    )

    foreach ($TaskNum in $TaskNums) {
        do something $TaskNum
    }
}

Here is a working example:

function Do-Something { 
    [CmdletBinding()]
    param (
        [Parameter(ValueFromRemainingArguments = $true)]
        [int[]] $TaskNumber
    )

    foreach ($Item in $TaskNumber) {
        Write-Verbose -Message ('Processing item: {0}' -f $Item);
    }
}

Do-Something 1 2 3 -Verbose;

Result:

enter image description here