问题
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