Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...