我可以以 Unix 方式将参数传递给 Powershell 函数吗? [英] Can I Pass Arguments To A Powershell Function The Unix Way?

查看:66
本文介绍了我可以以 Unix 方式将参数传递给 Powershell 函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基本上如下所示的 PowerShell 函数:

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

..然后像这样

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.

有什么方法可以编写一个与1 2 3"参数示例一起使用的 PS 函数?

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

推荐答案

是的,您可以使用 ValueFromRemainingArguments 参数属性.

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
    }
}

这是一个工作示例:

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;

结果:

这篇关于我可以以 Unix 方式将参数传递给 Powershell 函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆