Can I Pass Arguments To A Powershell Function The Unix Way?

末鹿安然 提交于 2020-01-11 05:40:08

问题


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?


回答1:


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:



来源:https://stackoverflow.com/questions/21340189/can-i-pass-arguments-to-a-powershell-function-the-unix-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!